使用纯色创建多个UIImage

时间:2013-12-06 16:40:27

标签: ios objective-c

我一直在寻找一种以编程方式绘制图像的方法。我找到了一个相当不错的解决方案:

UIGraphicsBeginImageContextWithOptions(CGSizeMake(36, 36), NO, 0.0);
UIImage *blank = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

但缺点是在同一个环境中我不能创建两个或多个不同颜色的图像,因此我可以将它们用作例如按钮的背景(对于所有三种状态)。是的,我知道我可以将一些资源PNG设置为UIButton的背景,但如果我想要,我就不会问这个问题。

我真的想学习如何以编程方式创建图像并使用它们,以不同的颜色作为背景,在相同的上下文中,或者可能在另一个上下文中创建,但移植到我需要的地方。

编辑:为了进一步澄清,请使用以下代码:

UIButton *button = [UIButton alloc] init];

button.frame = CGRectMake(0.0, 0.0, 200, 30);

//this is pefect
button.backgroundColor = [UIColor whiteColor];

//but, what if I want to have the UIControlStateNormal / UIControlStateHighlighted / UIControlStateDisabled with different background colors ?
[button setBackgroundColor: [UIColor blackColor] forState: ?] // dont't think so, right ?

在上面的情况下,我被迫使用一个图像,如果我希望按钮在按下或禁用时看起来不同,当然还有背景,因为标题和标题颜色可以很容易地改变。

4 个答案:

答案 0 :(得分:3)

您可以在UIImage上创建一个类别,以返回具有特定大小并填充颜色的新UIImage实例:

+ (UIImage *)imageOfSize:(CGSize)size filledWithColor:(UIColor *)color {
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect rect = (CGRect){CGPointZero, size};
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

答案 1 :(得分:2)

我创建了一个提供[UIImage imageWithColor:]的CocoaPod:

pod 'UIImage+ImageWithColor'

答案 2 :(得分:1)

看看这个:

+ (UIImage *)imageWithColor:(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 *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

您可以选择从图层

中绘制自定义图像
+ (UIImage *)imageFromLayer:(CALayer *)layer{
    UIGraphicsBeginImageContext([layer frame].size);
    [layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return outputImage;
}

答案 3 :(得分:0)

尝试使用相同的代码: -

    UIImage *thumbnail =[UIImage imageNamed:@"yourImg.png"];
    CGSize itemSize = CGSizeMake(35, 35);
    UIGraphicsBeginImageContext(itemSize);
    CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
    [thumbnail drawInRect:imageRect];
    cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();