2013-03-27 109 views
2

我正在將OS中的CALayer移植到iOS。CALayer未呈現其UIImage內容

我創建單個視圖應用中,束中複製的圖像「body.png」,並定義了UIView子類:

我希望這種方法添加一個層顯示圖像時我觸摸屏幕時,但圖像不顯示,只顯示框架。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 

UITouch * aTouch = [touches anyObject]; 
CGPoint loc = [aTouch locationInView:self]; 
CGPoint p=loc; 
CALayer * body = [CALayer layer]; 
UIImage * img =[UIImage imageNamed:@"body.png"]; 
[body setBounds:CGRectMake(0, 0, 200, 200)]; 
[body setPosition:p]; 

if (img) { 
    NSLog(@"body.png loaded"); 
     [body setBorderWidth:1]; 
     [body setBorderColor:[[UIColor blackColor] CGColor]]; 
     [body setContents:(id)img]; 
    } 
    else { 
     [body setBackgroundColor:[[UIColor blueColor] CGColor]]; 
    NSLog(@"body.png not loaded"); 
    } 

    [[self layer] addSublayer:body]; 
} 

我錯過了什麼?

+0

看看這個[文章] [1] - 可能你需要img.CGImage。 [1]:http://stackoverflow.com/questions/598659/calayer-not-rendering-when-added-after-view-visible –

回答

2

更改線路

[body setContents:(id)img]; 

[body setContents:(id)img.CGImage]; 
+0

感謝。 iOS上的CALayer似乎無法單獨從UIImage獲取CGImage。 – alecail