如何在swift中以菱形显示图像?

时间:2016-06-29 04:57:35

标签: ios swift uiimageview

Image

当我给出宽度和高度120并应用角落时,我想以菱形显示图像。我大致得到钻石形状,但没有得到精确的钻石形状,所以任何人都建议我对我有帮助。

self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2
self.imageView.clipsToBounds = true

2 个答案:

答案 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

产量:

enter image description here

对于Swift 2的演绎,请参阅previous revision of this answer

圆角的替代算法可能是:

imageView.addDiamondMask()

在这里,我正在角落里做四边形贝塞尔,但我认为如果钻石完全伸长,圆角的效果会比上面的效果略好。

无论如何,这会产生:

enter image description here

答案 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
    }
}
相关问题