我知道如何使用以下代码以编程方式创建 UIImage:
CGRect rect = CGRectMake(0.0f, 0.0f, 300.0f, 60.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
我想做的是用多种颜色填充它。像下面这样
最佳答案
您知道如何绘制一个矩形,只需推断绘制多个矩形,如下所示。使用您自己的颜色。我使用了内置颜色,如果需要任何自定义颜色,则使用 RGB 值设置颜色。
CGRect rect = CGRectMake(0.0f, 0.0f, 300.0f, 60.0f);
NSArray *colorArray = [NSArray arrayWithObjects:[UIColor redColor],[UIColor yellowColor],[UIColor greenColor],[UIColor brownColor],
[UIColor lightGrayColor],nil];
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
for (int i = 0; i < colorArray.count; i++)
{
CGRect smallRect = CGRectMake((300.0f /colorArray.count) * i,0.0f,(300.0f /colorArray.count) ,60.0f);
CGContextSetFillColorWithColor(context, [colorArray[i] CGColor]);
CGContextFillRect(context, smallRect);
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
关于objective-c - 以编程方式创建具有多种填充颜色的 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23948115/