你好,歡迎來到IOS教程網

 Ios教程網 >> IOS使用技巧 >> IOS技巧綜合 >> IOS Quartz2D 通過UIColor生成圖片

IOS Quartz2D 通過UIColor生成圖片

編輯:IOS技巧綜合
[摘要]本文是對IOS Quartz2D 通過UIColor生成圖片的講解,對學習IOS蘋果軟件開發有所幫助,與大家分享。

普通生成

示例代碼:

//這裡實現普通生成圖片的方法
- (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]);
}

效果圖:

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved