swift - 如何在 Swift 中创建直角 View ?

标签 swift uiview

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

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)

}

现在的问题是我想使用变换属性将其更改为直角三角形。如何做到这一点?

预期结果

enter image description here

当前结果

enter image description here

最佳答案

我希望你想要这部分。 enter image description here

这是代码。

override func draw(_ rect: CGRect) {

    let path = UIBezierPath.init()

    // top left
    path.move(to: .zero)

    // top right
    path.addLine(to: CGPoint(x: bounds.size.width,
                             y: 0))

    // bottom left offset
    path.addLine(to: CGPoint(x: bounds.size.width * 0.1,
                             y: bounds.size.height))

    // bottom left
    path.addLine(to: CGPoint(x: 0,
                             y: bounds.size.height))

    // top left
    path.close()

    // change fill color here.
    UIColor.black.setFill()
    path.fill()
}

结果 enter image description here

我是怎么画的

enter image description here

修改

如果将代码 UIColor.black.setFill() 更改为

let fillColor = UIColor(red: 0xF9/0xff, green: 0x0D/0xff, blue: 0x5A/0xff, alpha: 1)
    fillColor.setFill()

你得到了这个结果。 enter image description here

享受编码的乐趣。

关于swift - 如何在 Swift 中创建直角 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53257685/

相关文章:

ios - 方法 load() 定义了 Objective-C 类方法 'load' ,这是 Swift 1.2 不允许的

ios - NSArray转Swift Array后Array为空

ios - 通过自动布局根据 UILabel 的内容自动调整 UIView 的大小

iOS 8 UIView 没有得到更新的问题

iphone - UIView 图层未随 View 调整大小?

ios - CollectionView 和 CompletionHandler

ios - 从一个文本字段移动到另一个

ios - GCD 通过cancellable_dispatch_after 停止

ios - 将 UILabel 的基类 UIView 更改为自定义 UIView?

iOS:将 UIView 放在 UITableView 之上的固定位置