objective-c - 以编程方式创建具有多种填充颜色的 UIImage

标签 objective-c

我知道如何使用以下代码以编程方式创建 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();

我想做的是用多种颜色填充它。像下面这样

enter image description here

最佳答案

您知道如何绘制一个矩形,只需推断绘制多个矩形,如下所示。使用您自己的颜色。我使用了内置颜色,如果需要任何自定义颜色,则使用 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/

相关文章:

ios - 倒计时错误(NSDate 和 Objective-C)

objective-c - 我可以将非 xib 应用程序转换为使用 xibs 吗?

ios - map 中的随机 MKPointAnnotation

ios - 为什么我无法运行 "pod update"?

iPhone GPS - 未收到有效的位置更新

ios - 本地址栏中只有前缀时,使 iphone webview 转到不同的网址

objective-c - Objective-C 是否逐行运行代码?

ios - 用于核心数据搜索的 NSPredicate

javascript - OS X 上的 WebKit : How to detect a JS call to pushState() in a WebView?

objective-c - 使用 dispatch_get_main_queue() 运行 block 不起作用并挂起应用程序