我正在制作一个游戏并需要一个底部的尖峰,我决定通过UIView和碰撞来做。我正在快速编码。
我目前有一个广场:
//Object Setup
let square = UIView(frame: CGRect(x:100, y:100, width: 100, height: 100))
square.backgroundColor = UIColor.purpleColor()
view.addSubview(square)
我想要一个三角形,我确实有一个可用于三角形的图像,但图像是方形的,所以当碰到图像边界而不是实际的三角形边界时,肯定会发生碰撞请告知如何做与图像或我如何方格。
由于
亚历
答案 0 :(得分:33)
UIView
TriangleView
子类的新文件
TriangleView
类TriangleView
或以编程方式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
}
}
答案 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)
}