iOS 繪製純色圖片與漸變色圖片

一、繪製純色圖片

+(UIImage*) createImageWithColor:(UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

二、繪製漸變色圖片

/**
*  繪製漸變色的矩形UIImage
*
*  @param bounds       UIImage的bounds
*  @param colors       漸變色數組,可以設置兩種顏色
*  @param gradientType 漸變的方式:0:水平漸變   1:豎直漸變   2:向下對角線漸變   3:向上對角線漸變
*
*  @return 漸變色的UIImage
*/
+ (UIImage*)createGradientRectImageWithBounds:(CGRect)bounds Colors:(NSArray*)colors GradientType:(int)gradientType{
    NSMutableArray *cgcolorArr = [NSMutableArray array];
    for(UIColor *col in colors) {
        [cgcolorArr addObject:(id)col.CGColor];
    }
    UIGraphicsBeginImageContextWithOptions(bounds.size, YES, 1);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)cgcolorArr, NULL);
    CGPoint startPoint = CGPointMake(0.0, 0.0);
    if (gradientType == 3) {
        startPoint = CGPointMake(0.0, bounds.size.height);
    }
    CGPoint endPoint = CGPointZero;
    switch (gradientType) {
        case 0:
            endPoint = CGPointMake(bounds.size.width, 0.0);
            break;
        case 1:
            endPoint = CGPointMake(0.0, bounds.size.width);
            break;
        case 2:
            endPoint = CGPointMake(bounds.size.width, bounds.size.height);
            break;
        case 3:
            endPoint = CGPointMake(bounds.size.width, 0.0);
            break;
        default:
            break;
    }
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
    CGColorSpaceRelease(colorSpace);
    UIGraphicsEndImageContext();
    return image;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章