我問了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