在 CGImage 上画线

Drawing lines on top of CGImage

我目前正在尝试开发一个绘图应用程序。我遇到的问题是优化应用程序的性能。

我已经对 UIView 进行了子类化,我在其中检测用户的输入。

起初我尝试用 draw(_ rect: CGRect) 方法用 CoreGraphics 绘制所有线条,但是当线条数达到 10 000+ 时,延迟非常明显。所以我想创建一个 CGImage,我会在每个 draw(...) 周期之后制作,然后当下一个绘制周期到来时,我会把新的线条放在那个 CGImage 的顶部,因此不会再次绘制所有以前的线条并且节省宝贵的时间。

我在 touchesBegan()touchesMoved() 方法中注册新行,然后调用 self.needsDisplay().

这是我目前使用的代码:

var mainImage: CGImage?
var newLines: [Line]

override func draw(_ rect: CGRect) {

    let context = UIGraphicsGetCurrentContext()

    //context?.translateBy(x: 0, y: bounds.height)
    //context?.scaleBy(x: 1, y: -1)

    if let image = mainImage {
        context?.draw(image, in: bounds)
    }

    for line in newLines {
        context?.setStrokeColor(UIColor.black.cgColor)
        context?.setLineWidth(1)

        context?.move(to: line.previousLocation)
        context?.addLine(to: line.location)

        context?.strokePath()
    }
    newLines = []

    mainImage = context?.makeImage()
}

现在的问题是我画的线被分成两部分并且是垂直镜像的。 (Image split vertically)。我在这里画了两条连续的线——一条直线和一条曲线。奇怪的是,如果我翻转 UIView 的一半,线条将连续对齐,它们之间没有 space。

如果我取消注释前面提到的代码中的两行(context?.translateBy(x: 0, y: bounds.height)context?.scaleBy(x: 1, y: -1)),image would look like this.

现在唯一的错误是我在屏幕的下侧绘图并在上侧得到结果。

如何更正?我的问题的正确解决方案是什么?

非常感谢!

当您注释掉这两行时,您并未对图形上下文进行任何更改。如果您取消注释它们,那么您将在每次调用时更改上下文而不是保存它。所以我认为你基本上每次都在翻转它。不确定是否是这样,但你绝对应该 pushing/saving 在绘图之前你的上下文(显然 restoring/popping 它)。

看看这个 post:using UIImage drawInRect still renders it upside down.