码迷,mamicode.com
首页 > 移动开发 > 详细

IOS Quartz2D 通过UIColor生成图片

时间:2017-06-18 22:44:48      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:send   raw   .com   uicolor   rgb   nsarray   颜色   rtp   图片   

普通生成

示例代码:

技术分享
//这里实现普通生成图片的方法
- (void)drawRect:(CGRect)rect {

    CGRect cxRect = CGRectMake(0, 0, 100, 100);
    
    UIGraphicsBeginImageContextWithOptions(cxRect.size, NO, 0);
    
    [[UIColor redColor] setFill];
    
    UIRectFill(cxRect);
    
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 20, 100, 100)];
    
    imageView.image = image;
    
    [self addSubview:imageView];
}
技术分享

效果图:

技术分享

渐变颜色生成

示例代码:

技术分享
//这里实现渐变颜色生成图片的方法
- (void)drawRect:(CGRect)rect {

    CGRect cxRect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContextWithOptions(cxRect.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIColor * beginColor = [UIColor greenColor];
    UIColor * endColor = [UIColor redColor];
    drawLinearGradient(context, cxRect, beginColor.CGColor, endColor.CGColor);
    CGContextRestoreGState(context);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 20, 100, 100)];
    
    imageView.image = image;
    
    [self addSubview:imageView];
}

void drawLinearGradient(CGContextRef context, CGRect rect, CGColorRef startColor, CGColorRef endColor)
{
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat locations[] = { 0.0, 1.0 };
    
    NSArray *colors = @[(__bridge id) startColor, (__bridge id) endColor];
    
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);
    CGPoint startPoint = CGPointMake(rect.size.width/2, 0);
    CGPoint endPoint = CGPointMake(rect.size.width/2, rect.size.height/1.5);
    
    CGContextSaveGState(context);
    CGContextAddRect(context, rect);
    CGContextClip(context);
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
    CGContextSetStrokeColorWithColor(context, [[UIColor clearColor] CGColor]);
}
技术分享

效果图:

技术分享

 

IOS Quartz2D 通过UIColor生成图片

标签:send   raw   .com   uicolor   rgb   nsarray   颜色   rtp   图片   

原文地址:http://www.cnblogs.com/wuyuxin/p/7045626.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!