简体   繁体   中英

Making a triangle in a UIView with a CGRect Frame

HI I am making a game and need a spike at the bottom which I have decided to do via a UIView and collisions. I am coding in swift.

I currently have a square:

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

And I would like a triangle, I do have an image which I can use for a triangle but the image is square so surely the collision would be when it touches the image borders not the actual trianlge borders please advice on how to do with image or how I got square.

Thanks

Alex

Steps:

  1. Create a new file that subclasses UIView called TriangleView
  2. Paste this into the TriangleView class
  3. Add a TriangleView through XIB or programmatically

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
    }
}

Result:

三角形通过快速代码

There is tutorial here:

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

with code like this:

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM