如何在不使用imageview的情况下直接在视图上将图像设置为背景?

时间:2017-07-20 12:51:48

标签: ios objective-c uiview uiimageview xcode-storyboard

 UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"background.jpg"]];
    _mainView.backgroundColor = background;

当我运行此代码时,我在视图中将图像作为背景,但是像几个模式一样。我想在不使用ImageView的情况下将图像设置为我的视图。 是否可以通过stroyboard做?

2 个答案:

答案 0 :(得分:2)

您可以使用CaLayer对象,将图像指定为视图图层的内容。 其他项目可以像以前一样添加为视图的子视图。

class CustomViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // assign image as content of view's layer
        view.layer.contents = UIImage(named: "yourImageName")!.cgImage
    }   
} 

了解更多信息:

Apple's CALayer doc

CALayer tutorial

答案 1 :(得分:1)

  

当我运行此代码时,我在视图中将图像作为背景但是   像几种模式一样。

因为您创建了一个模式并将其设置为UIView。方法initWithPatternImage 使用指定的Quartz颜色参考初始化并返回颜色对象。

最好能使用UIImageView&将其添加到UIView