答案 0 :(得分:2)
使用本机渲染很容易做到这一点。一种方法是创建一个新视图并覆盖draw rect
方法。您可以执行以下操作:
class ViewWithFrame: UIView {
var color: UIColor = UIColor.black { didSet { setNeedsDisplay() } }
var lineThickness: CGFloat = 5 { didSet { setNeedsDisplay() } }
var lineLength: CGFloat = 30.0 { didSet { setNeedsDisplay() } }
override var frame: CGRect { didSet { setNeedsDisplay() } }
override func layoutSubviews() {
super.layoutSubviews()
setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
super.draw(rect)
var paths: [UIBezierPath] = [UIBezierPath]()
// Top left
paths.append({
let path = UIBezierPath()
path.move(to: .zero)
path.addLine(to: CGPoint(x: lineLength, y: 0.0))
path.addQuadCurve(to: CGPoint(x: lineLength-lineThickness, y: lineThickness), controlPoint: CGPoint(x: lineLength, y: lineThickness))
path.addLine(to: CGPoint(x: lineThickness, y: lineThickness))
path.addLine(to: CGPoint(x: lineThickness, y: lineLength-lineThickness))
path.addQuadCurve(to: CGPoint(x: 0.0, y: lineLength), controlPoint: CGPoint(x: lineThickness, y: lineLength))
path.close()
return path
}())
// Top right
paths.append({
let path = UIBezierPath()
path.move(to: CGPoint(x: frame.width, y: 0.0))
path.addLine(to: CGPoint(x: frame.width-lineLength, y: 0.0))
path.addQuadCurve(to: CGPoint(x: frame.width-(lineLength-lineThickness), y: lineThickness), controlPoint: CGPoint(x: frame.width-lineLength, y: lineThickness))
path.addLine(to: CGPoint(x: frame.width-lineThickness, y: lineThickness))
path.addLine(to: CGPoint(x: frame.width-lineThickness, y: lineLength-lineThickness))
path.addQuadCurve(to: CGPoint(x: frame.width, y: lineLength), controlPoint: CGPoint(x: frame.width-lineThickness, y: lineLength))
path.close()
return path
}())
// TODO: add 2 bottom paths
color.setFill()
paths.forEach { $0.fill() }
}
}
仍然需要绘制底部,但我希望您知道如何实现。
注意所有对setNeedsDisplay
的呼叫。这就是在下一个运行循环中触发draw rect
方法的原因,它应该对可能影响图形的视图的每次更改(包括视图大小)进行触发。