2017-01-30 77 views
0

我試圖繪製一個垂直翻轉其中心的圓。 (翻轉中心看起來相同,以便我可以直觀地查看)。但是,所畫的位置是完全錯誤的。我想到的是,填充有在描邊區域 enter image description here在drawrect方法內翻轉CGContext繪製錯誤的位置

circleRect = CGRect(x:100, y:100, width:100, height: 100) 

override func draw(_ dirtyRect: CGRect) { 
    let ctx = NSGraphicsContext.current()!.cgContext 
    if(drawCircle) { 
     let path = getOvalPath(circleRect) //returns a oval cgpath for the rect, here the rect is a square so it gives a circle 

     //stroked without flipping 
     ctx.addPath(path) 
     ctx.setStrokeColor(CGColor.black) 
     ctx.strokePath() 

     //filled with flipping 
     ctx.saveGState 
     ctx.translateBy(x: 0, y: circleRect.size.height) 
     ctx.scaleBy(x: 1, y: -1) 

     ctx.addPath(path) 
     ctx.setFillColor(fillColor) 
     ctx.fillPath() 
     ctx.restoreGState() 
} 

drawCircle = true 
setNeedsDisplay(circleRect) 

回答

1

你圓的中心在(100,100)內完全發生。考慮你在這一點上的變換效果:

var point = CGPoint(x: 100, y: 100) 
// point = (100, 100) 

point = point.applying(CGAffineTransform(scaleX: 1, y: -1)) 
// point = (100, -100) 

point = point.applying(CGAffineTransform(translationX: 0, y: 100)) 
// point = (100, 0) 

所以你的變換移動圓的中心。

您正在考慮「翻轉」y軸,將它從某個「畫布」的左下角移至左上角。如果它在該畫布上垂直居中,則您的圈子將保持放置狀態。您的畫布高度由您應用的y翻譯隱式定義,因此您的畫布高度爲100,這意味着圓圈的中心需要在y = 100/2 = 50處才能保持放置。

由於您的圓的中心位於y = 100,因此您需要使用2 * 100 = 200的畫布高度來使圓保持放置狀態。

+0

哪一個更好,改變上下文或路徑?例如,如果我想繪製一個旋轉了一定程度的形狀,那麼我可以在形狀路徑上進行旋轉變換,或者在繪製時旋轉上下文以實現它。 –

+0

無論哪一個讓你的代碼更簡單更好。這取決於情況。 –