2017-09-02 80 views
1

我創建的空灰色的UIImage,使用下面的代碼框架和圖像的特定的長寬比

let size = CGSize(width: 212, height: 332) 

UIGraphicsBeginImageContextWithOptions(size, true, 0) 
UIColor.gray.setFill() 
UIRectFill(CGRect(x: 0, y: 0, width: size.width, height: size.height)) 
let backgroundImage2: UIImage? = UIGraphicsGetImageFromCurrentImageContext() 
UIGraphicsEndImageContext() 

它顯示輸出 enter image description here

現在我需要把UIImage的特定的區域在該UIImage的。如下圖所示。說頂部,左邊,右邊應該是30像素,底部多於200像素。保持內部圖像寬高比。

enter image description here

+0

可以使用drawInRect方法來繪製圖像,並添加按照規定矩形。那你需要什麼? –

+0

@MikeAlter我做到了這一點,但問題是在進行Draw時保持寬高比(in:rect:) –

+0

即使您在最後進行小型演示,您也將面臨相同的長寬比問題@MikeAlter –

回答

0

使用兩圖像視圖(或者UIImageViewGLKView),使得「圖像」中的「灰色背景」視圖的子視圖。正確定位「圖像」後,將兩個圖像合併爲一個。

下面是一個擴展UIView,我使用:

extension UIView { 
    public func createImage() -> UIImage { 
     UIGraphicsBeginImageContextWithOptions(
      CGSize(width: self.frame.width, height: self.frame.height), true, 1) 
     self.layer.render(in: UIGraphicsGetCurrentContext()!) 
     let image = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 
     return image! 
    } 
}