ios - 在 CGImage 上画线

标签 ios swift core-graphics

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

我已经对 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 的一半,线条将连续对齐,它们之间没有空格。

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

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

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

非常感谢!

最佳答案

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

查看这篇文章:using UIImage drawInRect still renders it upside down.

关于ios - 在 CGImage 上画线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39874896/

相关文章:

xcode - CGContextSaveGState : invalid context 0x0 Error only on device

iphone - CGContextStrokeRect 仅绘制矩形的一侧

ios - 导致错误的 UIAlertView 按钮操作

ios - 打包 iOS 应用程序后推送通知停止工作

ios - How to subclass a renamed class?/'MKPinAnnotationView' was deprecated in iOS 15.0 : renamed to 'MKMarkerAnnotationView‘

ios - 在 spritekit 中保存锁定和解锁的游戏关卡

ios - 在我将我的 IOS 应用程序提交到 AppStore 后,AdMob 没有显示广告

ios - 在核心图形中传递 CGFloat 数组

Swift 组合改变了一系列出版商

Swift 快速/灵活 : Ambiguous use of expect