所以我正在做一个游戏,在这个游戏中,我投放的物体必须被用户在屏幕底部的钉子(三角形)摧毁。
我想不出怎么做一个三角形的UIView。然而,我已经能够让它像这样作为一个矩形工作:
let barrier = UIView(frame: CGRect(x:125, y: 650, width: 130, height:20))
barrier.backgroundColor = UIColor.orangeColor()
view.addSubview(barrier)
这已经奏效了。但是我想不出怎么做一个三角形。我想要它作为UIView的原因是因为我在它上面使用了碰撞,并且用户可以移动它。我尝试过PNG三角形,但它将碰撞检测为图像的边界,而不是三角形的起点。
我试过了,但它不起作用。
let square = UIView(frame: CGPathMoveToPoint(path, nil, 50, 0), CGPathAddLineToPoint(path, nil, 100, 50), CGPathAddLineToPoint(path, nil, 0, 100))
square.backgroundColor = UIColor.purpleColor()
view.addSubview(square)
任何帮助都将不胜感激,
谢谢,
亚历克斯
发布于 2015-06-05 03:19:56
CAShapeLayer它可以改变图层的形状。
var mask = CAShapeLayer()
mask.frame = self.layer.bounds
let width = self.layer.frame.size.width
let height = self.layer.frame.size.height
var path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 30, 0)
CGPathAddLineToPoint(path, nil, width, 0)
CGPathAddLineToPoint(path, nil, width, height)
CGPathAddLineToPoint(path, nil, 0, height)
CGPathAddLineToPoint(path, nil, 30, 0)
mask.path = path
// CGPathRelease(path); - not needed
self.layer.mask = mask
var shape = CAShapeLayer()
shape.frame = self.bounds
shape.path = path
shape.lineWidth = 3.0
shape.strokeColor = UIColor.whiteColor().CGColor
shape.fillColor = UIColor.clearColor().CGColor
self.layer.insertSublayer(shape, atIndex: 0)
发布于 2017-12-01 01:38:31
我稍微修改了前面的代码,添加了边距和填充颜色作为可检查的颜色,它在Swift4中工作得很好:
import UIKit
@IBDesignable
class TriangleView : UIView {
var _color: UIColor! = UIColor.blue
var _margin: CGFloat! = 0
@IBInspectable var margin: Double {
get { return Double(_margin)}
set { _margin = CGFloat(newValue)}
}
@IBInspectable var fillColor: UIColor? {
get { return _color }
set{ _color = newValue }
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
context.beginPath()
context.move(to: CGPoint(x: rect.minX + _margin, y: rect.maxY - _margin))
context.addLine(to: CGPoint(x: rect.maxX - _margin, y: rect.maxY - _margin))
context.addLine(to: CGPoint(x: (rect.maxX / 2.0), y: rect.minY + _margin))
context.closePath()
context.setFillColor(_color.cgColor)
context.fillPath()
}
}
https://stackoverflow.com/questions/30650343
复制相似问题