美文网首页
2022-01-12 iOS 渐变色按钮

2022-01-12 iOS 渐变色按钮

作者: yalahabawa | 来源:发表于2022-01-12 11:32 被阅读0次

先用下面的方法生成一张渐变色图片

具体的渐变方向改CGContextDrawLinearGradient参数,或者用其他样式的渐变,例如CGContextDrawRadialGradient

- (UIImage *)createImageWithSize:(CGSize)imageSize gradientColors:(NSArray *)colors percentage:(CGFloat)percents {
    NSMutableArray *ar = [NSMutableArray array];
    for(UIColor *c in colors) {
        [ar addObject:(id)c.CGColor];
    }
    UIGraphicsBeginImageContextWithOptions(imageSize, YES, 1);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, &percents);
    CGPoint start = CGPointMake(0.0, 0.0);
    CGPoint end = CGPointMake(imageSize.width, imageSize.height);
    CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
    CGColorSpaceRelease(colorSpace);
    UIGraphicsEndImageContext();
    return image;
}

用UIColor的类方法把图片转为颜色

  • (UIColor *)colorWithPatternImage:(UIImage *)image;

最后把颜色设置到button或者label即可

相关文章

网友评论

      本文标题:2022-01-12 iOS 渐变色按钮

      本文链接:https://www.haomeiwen.com/subject/cmqwcrtx.html