gpt4 book ai didi

ios - 在 Xcode for iOS 应用程序中使用 Swift 绘制性能

转载 作者:搜寻专家 更新时间:2023-11-01 06:43:45 25 4
gpt4 key购买 nike

我有一个画线的功能,在下面编辑。它在模拟器中似乎运行良好,但是在旧 iPhone (2011) 和较新 iPad (2014) 上运行时存在性能问题,线条绘制缓慢。我相信这个问题是由于为收到的每个 touchesMoved 事件创建一个新的 CGContext 造成的。

例如,我如何在 touchesBegan 时调用一次 let context = UIGraphicsGetCurrentContext()? (即如何使 context 成为可以调用一次的公共(public)变量?)

任何其他提高性能的技巧将不胜感激。谢谢。

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {

autoreleasepool {

UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0.0)

let context = UIGraphicsGetCurrentContext()

...
...
...

UIGraphicsEndImageContext()

}

}

最佳答案

不要在 touchesMoved 中执行绘图代码。您应该存储更新绘图所需的任何内容(可能是触摸位置),然后调用 setNeedsDisplay。这将强制调用包含所有绘图代码的 drawRect:。您无需创建上下文,只需使用 UIGraphicsGetCurrentContext()

这是一个人为设计的 UIView 子类示例,它在最新的触摸点下方绘制了一个红色圆圈。

class DrawView: UIView {

let circleSize:CGFloat = 50.0
var lastTouchPoint:CGPoint?

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
lastTouchPoint = touches.first?.locationInView(self)
self.setNeedsDisplay()
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
lastTouchPoint = touches.first?.locationInView(self)
self.setNeedsDisplay()
}

override func drawRect(rect: CGRect) {
if let touchPoint = lastTouchPoint {
let context = UIGraphicsGetCurrentContext()
CGContextSetRGBFillColor (context, 1, 0, 0, 1);
CGContextFillEllipseInRect(context, CGRectMake(touchPoint.x - circleSize/2.0, touchPoint.y - circleSize/2.0, circleSize , circleSize))
}
}
}

关于ios - 在 Xcode for iOS 应用程序中使用 Swift 绘制性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32768144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com