2009-09-07 29 views
0

我一直想寫使用Quartz一個層上的形象,但我看到的是完全空的圖片...這是代碼誤差UIGraphicsGetCurrentContext

CGContextRef context = UIGraphicsGetCurrentContext(); 

CGRect backRect = CGRectMake (0, 0, image.size.width, image.size.height); 

CGLayerRef backLayer = CGLayerCreateWithContext (context, image.size, NULL); 
CGContextRef backContext = CGLayerGetContext (backLayer); 

CGContextDrawImage(backContext, backRect, image.CGImage); 

你們可以告訴我什麼是錯的用這個代碼?

圖像是用相機拍攝的UIImage。

是的,圖像在那裏。如果我用

替換上述代碼
UIGraphicsBeginImageContext(image.size); 
[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)]; 

我看到圖像。但是我必須把它放在一個層面上,因爲它是一個精靈。

回答

1

覆蓋你不是真的這樣做與您所創建的任何一層。你應該使用CGContextDrawLayerAtPoint()或CGContextDrawLayerInRect()或將其添加到當前上下文...

你可以添加以下內容:

CGContextDrawLayerInRect(context, backRect, backLayer); 

CGContextDrawLayerAtPoint(context,CGPointZero,backLayer); 
+0

行CGContextDrawImage(backContext,backRect,image.CGImage);?它不是在上下文上繪製圖層嗎? – SpaceDog 2009-09-07 21:00:55

+0

不,您在創建的新圖層上繪製圖像,但圖層本身應添加到當前上下文中。 – 2009-09-07 21:03:01

+0

啊,好的。我已經添加了行\t CGContextDrawLayerAtPoint(context,CGPointMake(0,0),backLayer);在代碼的最後,我仍然得到空的圖像......我的頭髮在絕望中變得灰暗...... – SpaceDog 2009-09-07 21:10:08

0
  • 確定圖像是在正確的地方找到的嗎?
  • 此iPhone支持的圖像格式和顏色數量?
  • 圖像不會被其他繪圖調用透支?
  • 在最壞的情況下,未檢測到內存泄漏引起的圖像在內存
+0

一切都在那裏。如果我在此代碼前面添加行 UIGraphicsBeginImageContext(image.size); [image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)]; 圖像繪製正確。 – SpaceDog 2009-09-07 20:56:04

1

要知道,一個CGLayer與CALayer不同。 CALayer是Core Animation的動畫,CGLayer只是將靜態2D核心圖形繪製在一起的一種便利。因爲你把這個稱爲精靈,所以我假設你會想要這個動畫,所以CALayer會是更好的選擇。

我推薦閱讀Core Animation Programming Guide,特別是section on providing layer content。 CALayers在動畫方面會給你帶來非常好的性能,因爲它們是GPU加速的,不需要每一幀重繪。核心圖形不會給你任何接近可接受的動畫性能的地方,因爲重繪是昂貴的操作。