我问了this question earlier,我正在尝试探索制作屏幕外图像的想法。绘制屏幕外的彩色正方形返回灰度图像
有什么地方出了问题 - 我认为可能是色彩空间?我已经将代码向下和向下煮沸,直到我最终可以用几行来演示问题。
我有一个ImageView的视图(称为iv)和一个按钮,当推,所谓的“推”
- (UIImage *) block:(CGSize)size {
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColor(context, CGColorGetComponents([UIColor redColor].CGColor));
CGContextFillRect (context, CGRectMake(0, 0, size.width, size.height));
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result;
}
- (IBAction) push {
self.iv.image = [self block:CGSizeMake(50.0,50.0)];
}
这里的问题是,代替在指定颜色绘制一个50×50块,它将它绘制在一片灰色阴影中,这导致我认为它是一个色彩空间错误。
我想同样的事情用
- (CGContextRef) createBitmapContextOfSize:(CGSize) size {
CGContextRef context = NULL;
CGColorSpaceRef colorSpace;
void * bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
bitmapBytesPerRow = (size.width * 4);
bitmapByteCount = (bitmapBytesPerRow * size.height);
colorSpace = CGColorSpaceCreateDeviceRGB();
bitmapData = malloc(bitmapByteCount);
if (bitmapData == NULL) {
fprintf (stderr, "Memory not allocated!");
return NULL;
}
context = CGBitmapContextCreate (bitmapData,
size.width,
size.height,
8, // bits per component
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);
//CGContextSetAllowsAntialiasing (context,NO);
if (context== NULL) {
free (bitmapData);
fprintf (stderr, "Context not created!");
return NULL;
}
CGColorSpaceRelease(colorSpace);
return context;
}
- (UIImage *) block:(CGSize)size {
UIGraphicsBeginImageContext(size);
CGContextRef context = [self createBitmapContextOfSize:size];
CGContextSetFillColor(context, CGColorGetComponents([UIColor blueColor].CGColor));
CGContextFillRect (context, CGRectMake(0, 0, size.width, size.height));
UIImage *result = [UIImage imageWithCGImage: CGBitmapContextCreateImage (context)];
CGContextRelease(context);
UIGraphicsEndImageContext();
return result;
}
具有相同结果的位图上下文。灰盒子不是(在这种情况下)是蓝盒子。
我敢肯定,如果我可以让这个工作一切都会遵循。
问题是我使用[UIColor whatever] .CGColor来制作我的CGColor。由于我无法解释的原因,CGContextSetRGBFillColor无法正常工作。那么我怀疑(但我还没有尝试过)CGContextSetFillColorWithColor会以相同的方式失败。 – Andiih 2010-03-06 13:53:57
我不同意。我相信这是什么CGContextSetFillColor预期和什么CGColorGetComponents返回之间的不匹配。例如,如果上下文的初始颜色空间是一个白色空间(与PostScript的行为相匹配),那么CGContextSetFillColor将只读取一个或两个(白色和alpha)组件,而不知道你给了它两个。使用'CGContextSetFillColorWithColor'还将设置色彩空间,防止不匹配。 – 2010-03-06 14:42:39
这肯定会符合我的观察。我会测试它并反馈。 – Andiih 2010-03-06 22:20:52