如何在 Swift 中创建直角视图? [英] How to create Right Angle View in Swift?

查看:38
本文介绍了如何在 Swift 中创建直角视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用下面的代码快速创建三角形视图-

I am able to create triangle view in swift using below code-

class TriangleView: UIView {

    override func draw(_ rect: CGRect) {

        // Get Height and Width
        let layerHeight = layer.frame.height
        let layerWidth = layer.frame.width

        // Create Path
        let bezierPath = UIBezierPath()

        // Draw Points
        bezierPath.move(to: CGPoint(x: 0, y: layerHeight))
        bezierPath.addLine(to: CGPoint(x: layerWidth, y: layerHeight))
        bezierPath.addLine(to: CGPoint(x: layerWidth / 2, y: 0))
        bezierPath.addLine(to: CGPoint(x: 0, y: layerHeight))
        bezierPath.close()

        // Apply Color
        UIColor.red.setFill()
        bezierPath.fill()

        // Mask to Path
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = bezierPath.cgPath
        layer.mask = shapeLayer
    }

}

  override func viewDidLoad() {
        super.viewDidLoad()

        let triangle = TriangleView(frame: CGRect(x: 0, y: 0, width: 55 , height: 60))
        triangle.backgroundColor = .white
        triangle.transform = CGAffineTransform(rotationAngle: .pi * 4.49)
        imageView.addSubview(triangle)

}

现在的问题是我想使用变换属性将其更改为直角三角形.如何实现这一目标?

Now problem is that I want to change it to the right angle triangle using transform properties. How to achieve this?

预期结果

当前结果

推荐答案

您当前正在绘制a".你想画'b'.

You're currently drawing 'a'. You want to draw 'b'.

extension UIBezierPath {

    convenience init(rightAngledTriangleInRect: CGRect, offset withOffset: CGFloat) {
        self.init()
        move(to: CGPoint(x: rect.minX, y: rect.minY))
        addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
        addLine(to: CGPoint(x: rect.minX + offset, y: rect.maxY))
        addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
        addLine(to: CGPoint(x: rect.minX, y: rect.minY))
        close()
    }
}

然后使用:

let path = UIBezierPath.init(rightAngledTriangleInRect: rect, withOffset: 20.0)

请注意,无需在贝塞尔路径指令的便利初始化中添加 self..

Note that there's no need to add self. in the convenience inits for the bezier path instructions.

如果您要进行大量绘图,我建议您添加一些这样的初始化程序,以使生活更轻松.

If you're doing a lot of drawing, I'd recommend adding a number of these inits to make life easier.

在您当前的 TriangleView 中使用:

To use in your current TriangleView:

class TriangleView: UIView {

    override func draw(_ rect: CGRect) {

        let path = UIBezierPath.init(rightAngledTriangleInRect: rect, withOffset: 20.0)
        let shape = CAShapeLayer()
        shape.path = path.cgPath

        // Set the mask
        layer.mask = shape
    }
}

这篇关于如何在 Swift 中创建直角视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆