简体   繁体   English

用颜色填充CGBitmapContext

[英]Fill CGBitmapContext with color

I'm trying to fill a CGBitmapContext with a solid red color and get CGImgRef, but image is all transparent. 我正在尝试用纯红色填充CGBitmapContext并获取CGImgRef,但是图像都是透明的。 Here's the code 这是代码

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL,
                                             1,
                                             1,
                                             8,
                                             0,
                                             colorSpace,
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGFloat components[] = {1.0,0.0,0.0,1.0};
CGContextSetFillColor(context, components);
CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
CGImageRef imgRef = CGBitmapContextCreateImage(context);

Please don't recommend using UIBezierPaths and other UIKit things. 请不要建议使用UIBezierPaths和其他UIKit。 I need to use CoreGraphics. 我需要使用CoreGraphics。

The problem is that you forgot to set a fill color space. 问题是您忘记设置填充颜色空间。 You must do that in order for CGContextSetFillColor to work correctly (because that tells it how many components to expect and how to interpret them). 必须执行此操作才能使CGContextSetFillColor正常工作(因为它告诉它期望有多少个组件以及如何解释它们)。 This works: 这有效:

CGFloat components[] = {1,0,0,1};
CGContextSetFillColorSpace(context, colorSpace); // <-- this was missing
CGContextSetFillColor(context, components);
// and now fill ...

problem was solved using CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor) ; 使用CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor)解决了问题; Btw, it would be interesting to know what i was doing wrong. 顺便说一句,知道我做错了会很有趣。 Also Apple documentation on CGContextSetFillColor says "Note that the preferred API to use is now CGContextSetFillColorWithColor." 苹果在CGContextSetFillColor上的文档也说:“请注意,现在首选使用的API是CGContextSetFillColorWithColor。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM