在 drawrect 方法中翻转 CGContext 绘制在错误的位置
Flipping CGContext inside drawrect method draws in wrong posotion
我试着画了一个以圆心为中心垂直翻转的圆。 (以圆心翻转圆圈看起来一样,以便我可以目视检查)。但是绘制的位置是完全错误的。我希望填充必须完全发生在描边区域内
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)
您的圆心位于 (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 轴,将其从某个“canvas”的左下角移动到左上角。如果您的圆圈垂直居中于该 canvas,则它会保持不变。您的 canvas 的高度由您应用的 y 平移隐式定义,即 100。因此您的 canvas 的高度为 100,这意味着圆心需要位于 y = 100/2 = 50 留在原地。
由于您的圆心位于 y = 100,因此您需要使用 2*100 = 200 的 canvas 高度来使圆保持原样。
我试着画了一个以圆心为中心垂直翻转的圆。 (以圆心翻转圆圈看起来一样,以便我可以目视检查)。但是绘制的位置是完全错误的。我希望填充必须完全发生在描边区域内
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)
您的圆心位于 (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 轴,将其从某个“canvas”的左下角移动到左上角。如果您的圆圈垂直居中于该 canvas,则它会保持不变。您的 canvas 的高度由您应用的 y 平移隐式定义,即 100。因此您的 canvas 的高度为 100,这意味着圆心需要位于 y = 100/2 = 50 留在原地。
由于您的圆心位于 y = 100,因此您需要使用 2*100 = 200 的 canvas 高度来使圆保持原样。