在自定义颜色画布上绘制UIImage

时间:2013-08-15 14:40:11

标签: ios uiimage core-graphics

我想在黑色画布上绘制一个图像,但结果总是白色的,这是我的代码

-(UIImage*) renderImage
{
    UIGraphicsBeginImageContext(CGSizeMake(300, 300));
    [[UIColor blackColor] setFill];
    UIImage*resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultImage;
}

为了将来我将在画布内绘制一个图像,但是现在我只想要一个黑色的画布。为什么这段代码不起作用

1 个答案:

答案 0 :(得分:1)

您需要使用CGContextSetFillColorWithColor()用颜色填充当前上下文。试试这个示例代码,你给它一个颜色和大小,它会返回一个符合你标准的UIImage。

- (UIImage *)renderImageWithColor:(UIColor *)color inSize:(CGSize)size
{
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}
相关问题