简体   繁体   English

如何将UIView图像UIImageView设置为背景?

[英]How do I set a UIView image UIImageView to the background?

I have a custom view for which I've (in the XIB) created a UIImageView as a subview. 我有一个自定义视图,在XIB中已为其创建一个UIImageView作为子视图。 How can I make the image view appear in the background? 如何使图像视图出现在背景中? (ie so that in the custom view I can create the hands of a clock that will appear over the top) (即,这样,在自定义视图中,我可以创建将出现在顶部的时钟指针)

Do I need to make my background image have alpha areas for transparency? 我是否需要使背景图像具有透明的Alpha区域? (if I have the terms correct) Or is it OK to have an image with it's background just set to white or black or whatever it needs to be (on the basis it will be in the background so this will be ok) (如果我的用语正确)或者将背景设置为白色或黑色或需要设置的图像是否可以(在背景中为基础,这样就可以了)

You can't: views are composited on top of their superviews, which means if your custom view is drawing in -drawRect: , it will always appear under the UIImageView. 您不能:视图是在其超级视图之上合成的,这意味着如果您的自定义视图是在-drawRect:绘制的,它将始终出现在UIImageView下。

The easiest way to achieve the effect you're looking for is to put the image view under your custom view in IB. 实现所需效果的最简单方法是将图像视图置于IB中的自定义视图下。

Background images generally do not need to have transparency (and there's a slight speedup if the PNG has no alpha channel). 背景图像通常不需要透明(如果PNG没有Alpha通道,则速度会略有提高)。

An alternate approach to using UIImageView objects if you are drawing the rest of stuff in drawRect: is to use the image directly. 如果要在drawRect:中绘制其余内容,则使用UIImageView对象的另一种方法是直接使用图像。 Draw the image in drawRect: before you do any of the drawing. 在执行任何绘图之前,请在drawRect:绘制图像。

Example

- (void)drawRect:(CGRect)rect {
    [backgroundImage drawInRect:rect];

     /* Do rest of your drawing */
}

Now this is only if you are using a complex image. 现在仅当您使用复杂图像时。 If it is a texture, you would rather use UIColor 's colorWithPatternImage: method to get a color from the UIImage object and set your custom view's backgroundColor . 如果是纹理,则宁愿使用UIColorcolorWithPatternImage:方法从UIImage对象获取颜色并设置自定义视图的backgroundColor Remember that using the colorWithPatternImage: will not scale the image while drawing and will tile if the source image is smaller the frame of the view. 请记住,使用colorWithPatternImage:不会在绘制时缩放图像,如果源图像小于视图框架,则将平铺图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM