mah*_*ios 4 uiimageview ios swift

当我给出宽度和高度120并应用角落时,我想以菱形显示图像.我大约得到钻石形状但没有得到精确的钻石形状所以任何人都建议我对我有帮助.
self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2
self.imageView.clipsToBounds = true
Run Code Online (Sandbox Code Playgroud)
Rob*_*Rob 17
如果您有图像视图并想要将其裁剪为菱形(菱形)形状,您应该:
UIBezierPath于菱形;patha CAShapeLayer;CAShapeLayer为mask在的UIImageView的layer在Swift 3及更高版本中,它可能看起来像:
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
}
}
Run Code Online (Sandbox Code Playgroud)
因此,只需在图像视图上调用addDiamondMask(cornerRadius:)(在cornerRadius可选的位置).
imageView.addDiamondMask()
Run Code Online (Sandbox Code Playgroud)
产量:
对于Swift 2的演绎,请参阅此答案的上一版本.
用于圆角的替代算法可能是:
extension UIView {
func addDiamondMask(cornerRadius: CGFloat = 0) {
let path = UIBezierPath()
let points = [
CGPoint(x: bounds.midX, y: bounds.minY),
CGPoint(x: bounds.maxX, y: bounds.midY),
CGPoint(x: bounds.midX, y: bounds.maxY),
CGPoint(x: bounds.minX, y: bounds.midY)
]
path.move(to: point(from: points[0], to: points[1], distance: cornerRadius, fromStart: true))
for i in 0 ..< 4 {
path.addLine(to: point(from: points[i], to: points[(i + 1) % 4], distance: cornerRadius, fromStart: false))
path.addQuadCurve(to: point(from: points[(i + 1) % 4], to: points[(i + 2) % 4], distance: cornerRadius, fromStart: true), controlPoint: points[(i + 1) % 4])
}
path.close()
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.fillColor = UIColor.white.cgColor
shapeLayer.strokeColor = UIColor.clear.cgColor
layer.mask = shapeLayer
}
private func point(from point1: CGPoint, to point2: CGPoint, distance: CGFloat, fromStart: Bool) -> CGPoint {
let start: CGPoint
let end: CGPoint
if fromStart {
start = point1
end = point2
} else {
start = point2
end = point1
}
let angle = atan2(end.y - start.y, end.x - start.x)
return CGPoint(x: start.x + distance * cos(angle), y: start.y + distance * sin(angle))
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我正在角落里做四边形贝塞尔,但我认为如果钻石完全拉长,圆角的效果会略好于上面的效果.
无论如何,这产生:
| 归档时间: |
|
| 查看次数: |
1476 次 |
| 最近记录: |