美文网首页
iOS - 根据颜色生成图片

iOS - 根据颜色生成图片

作者: 随缘吖 | 来源:发表于2019-02-13 18:12 被阅读0次

- (UIImage *)getGradientImageFromColors:(NSArray*)colors  imgSize:(CGSize)imgSize
{
    CGRect rect = (CGRect){0.f, 0.f, imgSize};
    NSMutableArray *ar = [NSMutableArray array];
    for(UIColor *c in colors) {
        [ar addObject:(id)c.CGColor];
    }
    UIGraphicsBeginImageContextWithOptions(imgSize, NO, UIScreen.mainScreen.scale);
    CGContextAddPath(UIGraphicsGetCurrentContext(),
                     [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:24].CGPath);
    CGContextClip(UIGraphicsGetCurrentContext());
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, NULL);

    CGPoint   start = CGPointMake(0.0, 0.0);
    CGPoint  end = CGPointMake(imgSize.width, 0.0);

    CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
    CGColorSpaceRelease(colorSpace);
    UIGraphicsEndImageContext();
    return image;
}

相关文章

网友评论

      本文标题:iOS - 根据颜色生成图片

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