2010-01-19 7 views
1

我試圖加快我的繪圖代碼。不是創建圖形上下文,而是繪製當前圖像並繪製它,然後使用一些像素數據創建上下文,並直接修改該上下文。問題是,我對核心圖形非常新,而且我無法創建初始圖像。我只想得到一個穩固的紅色圖像,但我什麼也沒得到。以下是我用於初始圖像的內容。我認爲這個問題和其他代碼一樣。從Core Graphics上下文創建可重複使用的圖像不會給我帶來什麼

pixels = malloc(320*460*4); 
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
CGContextRef context = CGBitmapContextCreate(pixels, 320, 460, 8, 4*320, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); 
CGColorSpaceRelease(colorSpace); 

CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0); 
CGContextAddRect(context, CGRectMake(0, 0, 320, 460)); 
CGContextFillPath(context); 
trace = [[UIImageView alloc] initWithImage:UIGraphicsGetImageFromCurrentImageContext()]; 
CGContextRelease(context); 

編輯UIGraphicsGetImageFromCurrentImageContext()原來是這個問題。一個工作的解決方案如下,但是請注意,這是沒有快於簡單得多UIGraphicsBeginImageContext()

pixels = malloc(320*460*4); 
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
CGContextRef context = CGBitmapContextCreate(pixels, 320, 460, 8, 4*320, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); 

CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0); 
CGContextAddRect(context, CGRectMake(0, 0, 320, 460)); 
CGContextFillPath(context); 
CGDataProviderRef dp = CGDataProviderCreateWithData(NULL, pixels, 320*460*4, NULL); 
CGImageRef img = CGImageCreate(320, 460, 8, 32, 4*320, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big, dp, NULL, NO, kCGRenderingIntentDefault); 
trace = [[UIImageView alloc] initWithImage:[UIImage imageWithCGImage:img]]; 
CGImageRelease(img); 
CGColorSpaceRelease(colorSpace); 
CGContextRelease(context); 
+0

你真的應該在運行時得到應用程序窗口空間的矩形(即屏幕減去狀態欄),而不是硬編碼零原點和320×460尺寸。首先,您的代碼無法處理風景(例如,480×300)屏幕。另一方面,您的應用可以自動處理更大的屏幕尺寸(例如,在平板電腦上)。您可能需要使用' - [UIScreen applicationFrame:]':http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIScreen_Class/Reference/UIScreen.html#//apple_ref/occ/ instp/UIScreen/applicationFrame – 2010-01-20 04:24:45

回答

1

對於初學者來說,好像你正在繪製的背景是未連接到UIGraphics「當前圖像內容」。你在什麼地方打電話UIGraphicsBeginImageContext(CGSize size)

不知道你會得到你需要的東西,但它肯定意味着你不太可能將nil作爲當前圖像上下文。

+0

問題是如果我使用它,然後繪製它,我需要使用'UIGraphicsGetCurrentContext()'這不允許我使用像素數據,但謝謝指出我在右邊方向。我會嘗試替換'UIGraphicsGetImageFromCurrentImageContext()' – 2010-01-19 07:56:20

+0

我想我有點不確定你從根本上想要在這裏完成什麼。爲什麼你不能照常使用UIView子類,並在drawRect:call內部填充背景?圖像/位圖要求來自哪裏? – 2010-01-19 16:30:45

+0

我想我將不得不嘗試這條路線。由於這些更新發生得太快,重繪整個圖像需要很長時間。我希望能使用相同的源數據,只是改變一小部分。可悲的是,你的回答確實讓我朝着正確的方向前進,但那條路線也變得太慢了。我給你信貸,因爲你發現問題,並帶領我找到解決方案。謝謝你的幫助。 – 2010-01-19 17:21:06

相關問題