2017-03-17 97 views
2

enter image description here如何將圖像拉伸成自定義形狀(swift3)

下面的代碼列表會裁剪圖像。我希望圖像能夠變形/拉伸,而不是在形狀上裁剪。所有的圖像內容仍然在變換後的圖像中。它只會看起來不同。

extension UIImageView { 
func addMask(_ bezierPath: UIBezierPath) { 
    let pathMask = CAShapeLayer() 
    pathMask.path = bezierPath.cgPath 
    layer.mask = pathMask 
} 
    } 


    let myPicture = UIImage(data: try! Data(contentsOf: URL(string:"https://scontent-iad3-1.xx.fbcdn.net/v/t31.0-8/14196150_10207770295835716_3510332720585393213_o.jpg?oh=fdb525410602f40f4735991b713e9c50&oe=596688E5")!))! 
    let iv = UIImageView(image: myPicture) 

    let bezierPath = UIBezierPath() 
    bezierPath.move(to: iv.center) 
    bezierPath.addLine(to: CGPoint(x: iv.frame.maxX, y: 0)) 
    bezierPath.addLine(to: CGPoint(x: iv.frame.maxX, y: iv.frame.maxY)) 
    bezierPath.addLine(to: CGPoint(x: 0, y: iv.frame.maxY)) 
    bezierPath.addLine(to: .zero) 
    bezierPath.close() 

iv.addMask(bezierPath) 

回答

0

時,你必須顯示你可以使用圖像濾芯或者你可以嘗試圖像屏蔽這種類型的圖像..

圖像核心過濾:秀:

https://www.appcoda.com/core-image-introduction

https://code.tutsplus.com/tutorials/ios-sdk-apply-photo-filters-with-core-image-in-swift--cms-27142 

圖像遮蔽:

https://www.innofied.com/implementing-image-masking-in-ios/

我是盡我best..to提供solution..that是簡單的圖像

enter image description here

是面具形象是GIF類型的圖像

enter image description here

代碼寫

override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
     let image = UIImage(named: "image.gif") 
     let maskingImage = UIImage(named: "mask-image.gif") 
     imageView.image = maskImage(image: image!, mask: maskingImage!) 
    } 

func maskImage(image:UIImage, mask:(UIImage))->UIImage{ 

    let imageReference = image.cgImage 
    let maskReference = mask.cgImage 

    let imageMask = CGImage(maskWidth: maskReference!.width, 
          height: maskReference!.height, 
          bitsPerComponent: maskReference!.bitsPerComponent, 
          bitsPerPixel: maskReference!.bitsPerPixel, 
          bytesPerRow: maskReference!.bytesPerRow, 
          provider: maskReference!.dataProvider!, decode: nil, shouldInterpolate: true) 

    let maskedReference = imageReference!.masking(imageMask!) 

    let maskedImage = UIImage(cgImage:maskedReference!) 

    return maskedImage 
} 

最終結果 enter image description here

+0

https://www.innofied.com/implementing-image-masking-in-ios/這正是我期待的但它似乎是在swift2,而不是迅速的3 –

+0

如何如果您只是更改建議的編輯,則首先會比代碼更好地使用imageview。 –

+0

好吧,我會給你演示.. –