如何获取背景视图的背景图像使用init:pattern Image设置颜色

时间:2014-07-18 12:05:17

标签: ios swift

如果我将背景设置为我的视图:

let image:UIImage = UIImage(named: self.backgroundImages[self.backgroundImageIndex!])
self.view.backgroundColor = UIColor(patternImage:image)

我如何在另一个地方阅读背景的UIImage?

let image:UIImage = self.view.backgroundColor as UIImage  // Error

1 个答案:

答案 0 :(得分:1)

您无法使用现成的财产。您可以使用扩展名<{1>}创建自己的函数或将计算属性添加到UIView

extension UIView {
    var backgroundImage: UIImage! {
        let rect = self.frame
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        CGContextSetFillColorWithColor(context, self.backgroundColor.CGColor)
        CGContextFillRect(context, rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

然后将其与view.backgroundImage

一起使用
相关问题