iPhone:如何向UIView的根层添加图层以显示包含content属性的图像?

6 iphone

根据Mac Dev Center文档,您应该能够设置CALayer的contents属性并自动渲染.但是,我仍然无法通过稍后向UIView的根添加子层来显示简单的图像.我尝试了多种不同的变化; 这是我到目前为止所拥有的:

(注意:我知道还有其他渲染图像的方法;出于我的目的,我想将CALayer用于一些我将要进入的更复杂的东西).

(在ViewController的viewDidDisplay()中):

 CALayer *theLayer = [CALayer layer];
 [[[self view] layer] addSublayer:theLayer];
 theLayer.contents = (id)[[UIImage imageNamed:@"mypic.png"] CGImage];
 theLayer.contentsRect = CGRectMake(0.0f, 0.0f, 300.0f, 300.0f);
 theLayer.bounds = CGRectMake(0.0f, 0.0f, 300.0f, 400.0f);
Run Code Online (Sandbox Code Playgroud)

谁知道我做错了什么?

谢谢!

imn*_*mnk 5

您可以将图像加载到UIImageView中,该UIImageView是从UIView中删除的,因此具有自己的图层属性.

UIImageView *imgView = [[UIImageView alloc] initWithFrame:frame];
imgView.image = [UIImage imageNamed:@"mypic.png"];

[[[self view] layer] addSublayer:[imgView layer]];
[imgView release];
Run Code Online (Sandbox Code Playgroud)


Ben*_*ieb 1

您不需要设置contentsRect(如果您这样做,它应该在单位坐标空间中,可能只是CGRectMake(0, 0, 1.0, 1.0).

您可能想要设置 的layer属性position