我寫這個自定義UIView類繪製自定義形狀如何更改UIGraphicsGetCurrentContext的fillColor?
class ShapeView: UIView {
var color: UIColor?
init(frame: CGRect, color: UIColor) {
super.init(frame: frame)
self.color = color
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
super.draw(rect)
drawShape(rect: rect, color: self.color!)
}
func drawShape(rect: CGRect,color: UIColor) {
guard let ctx = UIGraphicsGetCurrentContext() else { return }
ctx.setFillColor(UIColor.clear.cgColor)
ctx.beginPath()
ctx.move(to: CGPoint(x: rect.width/2, y: 0))
ctx.addLine(to: CGPoint(x: rect.width, y: rect.height/2))
ctx.addLine(to: CGPoint(x: rect.width/2 , y: rect.height))
ctx.addLine(to: CGPoint(x: 0, y: rect.height/2))
ctx.closePath()
ctx.setFillColor(color.cgColor)
ctx.fillPath()
ctx.strokePath()
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let path = UIBezierPath(ovalIn: self.frame)
return path.contains(point)
}
,並在裏面的造型某處按下用戶我需要改變這種形狀的填充顏色,讓我們說黑與此代碼//調試時顏色沒有改變它看起來像我做錯了什麼。
在一些UIViewController類我寫這個方法
class SomeClass: UIViewController {
var shape1: ShapeView?
var frame: CGRect?
override func viewDidLoad() {
let x = view.frame.midX
let y = view.frame.midY
self.frame = CGRect(x: x, y: y, width: 100, height: 100)
super.viewDidLoad()
self.shape1 = ShapeView(frame: frame!, color: .red)
shape1?.backgroundColor = .clear
view.addSubview(shape1!)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let location = touches.first!.location(in: self.view)
if (shape1?.point(inside: location, with: event))! {
print("inside shape1")
shape1?.drawShape(rect: frame!, color: .black)
} else {
print("outside shape1")
shape1?.drawShape(rect: frame!, color: .red)
}
}
任何想法!
當你調用這個'如果(shape1 .point(內:位置,用:事件))!在另一個'ViewController'或在同一個'ShapeView'類 –
'''1'那裏有什麼'shape1'。shape1?.drawShape(rect:frame !, color:.black) } ..它是一個UIView –