2017-07-14 51 views
2

我要畫一個形狀,並檢測用戶觸摸的形狀或不裏面,所以我從UIView的定義自定義類繼承如下:UIGraphicsGetCurrentContext沒有出現內部的UIView

class ShapeView: UIView { 

    override init(frame: CGRect) { 
    super.init(frame: frame) 
    } 

    required init?(coder aDecoder: NSCoder) { 
    fatalError("init(coder:) has not been implemented") 
    } 

    override func draw(_ rect: CGRect) { 
    drawShape() 
    } 

    func drawShape() { 

    guard let ctx = UIGraphicsGetCurrentContext() else { return } 

    let zero = CGPoint(x: frame.midX, y: frame.midY) 

    let size: CGFloat = 50 

    ctx.beginPath() 
    ctx.move(to: .zero) 
    ctx.addLine(to: CGPoint(x: -size, y: -size)) 
    ctx.addLine(to: CGPoint(x: zero.x , y: (-size * 2))) 
    ctx.addLine(to: CGPoint(x: size, y: -size)) 
    ctx.closePath() 
    ctx.setFillColor(UIColor.red.cgColor) 
    ctx.fillPath() 
    } 

此代碼應繪製形狀像這樣

shape

override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { 
    let path = UIBezierPath(ovalIn: self.frame) 
    return path.contains(point) 
    } 
} 

,並在我的viewController寫了這個代碼,該自定義視圖添加到的UIViewController:

var shape: ShapeView? 

override func viewDidLoad() { 
    super.viewDidLoad() 

    let x = view.frame.midX 
    let y = view.frame.midY 

    self.shape = ShapeView(frame: CGRect(x: x, y: y, width: 100, height: 100)) 
    shape?.backgroundColor = .green 
    view.addSubview(shape!) 
} 

我知道形狀是裏面的觀點後,寫了這個方法:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    let location = touches.first!.location(in: self.view) 
    if (shape?.point(inside: location, with: event))! { 
     print("inside view") 
    } else { 
     print("outside view") 
    } 

,但總的結果是這樣的圖像,它只是有鑑於綠色的一種顏色,有一個子視圖,但沒有顏色出現

colored UIView with uncolored shape inside

那麼,什麼是錯與此代碼?

+1

你可能還需要調用'super.draw(矩形)'你重寫func'draw(_ rect:CGRect){}'函數 – Bacon

回答

2

您應該使用override func draw(_ rect: CGRect)rect的大小來進行計算。

我也覺得你的計算是不正確的,沒有測試過,但我想應該是這樣的:

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