使用CGRect框架在UIView中创建一个三角形

时间:2014-10-26 22:32:59

标签: ios uiview swift cgrect

我正在制作一个游戏并需要一个底部的尖峰,我决定通过UIView和碰撞来做。我正在快速编码。

我目前有一个广场:

        //Object Setup
        let square = UIView(frame: CGRect(x:100, y:100, width: 100, height: 100))
        square.backgroundColor = UIColor.purpleColor()
        view.addSubview(square)

我想要一个三角形,我确实有一个可用于三角形的图像,但图像是方形的,所以当碰到图像边界而不是实际的三角形边界时,肯定会发生碰撞请告知如何做与图像或我如何方格。

由于

亚历

2 个答案:

答案 0 :(得分:33)

步骤:

  1. 创建一个名为UIView
  2. TriangleView子类的新文件
  3. 将其粘贴到TriangleView
  4. 通过TriangleView或以编程方式
  5. 添加XIB
    import UIKit
    
    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.green.setFill()
            bezierPath.fill()
    
            // Mask to Path
            let shapeLayer = CAShapeLayer()
            shapeLayer.path = bezierPath.cgPath
            layer.mask = shapeLayer
        }
    }
    

    结果:

    Triangle via swift code

答案 1 :(得分:5)

这里有教程:

http://jamesonquave.com/blog/drawing-custom-views-with-swift-andrew-vanwagoner/

代码如下:

func drawPlayPathTo(context: CGContextRef, boundedBy rect: CGRect) {
  CGContextSetFillColorWithColor(context, UIColor.blackColor().CGColor)
  CGContextMoveToPoint(context, rect.width / 4, rect.height / 4)
  CGContextAddLineToPoint(context, rect.width * 3 / 4, rect.height / 2)
  CGContextAddLineToPoint(context, rect.width / 4, rect.height * 3 / 4)
  CGContextAddLineToPoint(context, rect.width / 4, rect.height / 4)
  CGContextFillPath(context)
}