当我给出宽度和高度120并应用角落时,我想以菱形显示图像。我大致得到钻石形状,但没有得到精确的钻石形状,所以任何人都建议我对我有帮助。
self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2
self.imageView.clipsToBounds = true
答案 0 :(得分:15)
如果您有图像视图并希望将其裁剪为菱形(菱形)形状,则应该:
UIBezierPath
; path
; CAShapeLayer
CAShapeLayer
设为mask
UIImageView
的{{1}} 在Swift 3及更高版本中,这可能看起来像:
layer
因此,只需在图片视图上调用extension UIView {
func addDiamondMask(cornerRadius: CGFloat = 0) {
let path = UIBezierPath()
path.move(to: CGPoint(x: bounds.midX, y: bounds.minY + cornerRadius))
path.addLine(to: CGPoint(x: bounds.maxX - cornerRadius, y: bounds.midY))
path.addLine(to: CGPoint(x: bounds.midX, y: bounds.maxY - cornerRadius))
path.addLine(to: CGPoint(x: bounds.minX + cornerRadius, y: bounds.midY))
path.close()
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.fillColor = UIColor.white.cgColor
shapeLayer.strokeColor = UIColor.white.cgColor
shapeLayer.lineWidth = cornerRadius * 2
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.lineCap = kCALineCapRound
layer.mask = shapeLayer
}
}
(addDiamondMask(cornerRadius:)
是可选的)。
cornerRadius
产量:
对于Swift 2的演绎,请参阅previous revision of this answer。
圆角的替代算法可能是:
imageView.addDiamondMask()
在这里,我正在角落里做四边形贝塞尔,但我认为如果钻石完全伸长,圆角的效果会比上面的效果略好。
无论如何,这会产生:
答案 1 :(得分:0)
SWIFT 5
extension UIView {
func addDiamondMask(cornerRadius: CGFloat = 0) {
let path = UIBezierPath()
path.move(to: CGPoint(x: bounds.midX, y: bounds.minY + cornerRadius))
path.addLine(to: CGPoint(x: bounds.maxX - cornerRadius, y: bounds.midY))
path.addLine(to: CGPoint(x: bounds.midX, y: bounds.maxY - cornerRadius))
path.addLine(to: CGPoint(x: bounds.minX + cornerRadius, y: bounds.midY))
path.close()
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.fillColor = UIColor.white.cgColor
shapeLayer.strokeColor = UIColor.white.cgColor
shapeLayer.lineWidth = cornerRadius * 2
shapeLayer.lineJoin = .round
shapeLayer.lineCap = .round
layer.mask = shapeLayer
}
}