我有一個具有圓角半徑和陰影的自定義視圖,並且我試圖在其中添加圖像。圖像應位於圓形區域內。但是,我在視圖中看到了一個黑色區域,圖像應該是這樣的(或者圖像是一個正方形,沒有圓角,在我最後一次嘗試時)。我如何添加此圖片?Swift - 將圖像添加到圓形視圖
錯誤的結果我得到:
我的代碼:
import Foundation
import UIKit
@IBDesignable
class RoundedSquareView: UIView {
var shadowLayer: CAShapeLayer!
@IBInspectable var image: UIImage! = UIImage()
override func layoutSubviews() {
super.layoutSubviews()
if shadowLayer == nil {
shadowLayer = CAShapeLayer()
shadowLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: 14).cgPath
shadowLayer.fillColor = UIColor.white.cgColor
shadowLayer.shadowColor = UIColor.darkGray.cgColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowOffset = CGSize(width: 0, height: 10.0)
shadowLayer.shadowOpacity = 0.3
shadowLayer.shadowRadius = 10
layer.insertSublayer(shadowLayer, at: 0)
}
let imgLayer = CAShapeLayer()
let myImage = image.cgImage
imgLayer.frame = bounds
imgLayer.masksToBounds = true
imgLayer.contents = myImage
imgLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: 14).cgPath
imgLayer.cornerRadius = 14
layer.addSublayer(imgLayer)
}
}
編輯:
預期的結果:
我已經在應用我想把這個圖像放在這個自定義的視圖上,視圖應該是圓的,有陰影,並且有一個圖像在裏面 –
Post edit。請看看我想要的結果, m試圖實現。 –
更新完整的擴展 – Frankie