在我的应用程序中,我创建了一个图像映射浮点到像素值,并将其用作Google地图上的叠加层,但这需要永远做,Android中的相同情况几乎是瞬间的。我的代码看起来像这样:Swift中的绘图图像永远需要
private func imageFromPixels(pixels: [PixelData], width: Int, height: Int) -> UIImage? {
let bitsPerComponent = 8
let bitsPerPixel = bitsPerComponent * 4
let bytesPerRow = bitsPerPixel * width/8
let providerRef = CGDataProvider(
data: NSData(bytes: pixels, length: height * width * 4)
)
let cgimage = CGImage(
width: width,
height: height,
bitsPerComponent: bitsPerComponent,
bitsPerPixel: bitsPerPixel,
bytesPerRow: bytesPerRow,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue),
provider: providerRef!,
decode: nil,
shouldInterpolate: true,
intent: .defaultIntent
)
if cgimage == nil {
print("CGImage is not supposed to be nil")
return nil
}
return UIImage(cgImage: cgimage!)
}
任何关于这可能需要这么长时间的建议吗?我可以看到它使用大约96%的CPU功率。
func fromData(pair: AllocationPair) -> UIImage? {
let table = pair.table
let data = pair.data
prepareColors(allocations: table.allocations)
let height = data.count
let width = data[0].count
var colors = [PixelData]()
for row in data {
for val in row {
if (val == 0.0) {
colors.append(PixelData(a: 0, r: 0, g: 0, b: 0))
continue
}
if let interval = findInterval(table: table, value: val) {
if let color = intervalColorDict[interval] {
colors.append(PixelData(a: color.a, r: color.r, g: color.g, b: color.b))
}
}
}
}
return imageFromPixels(pixels: colors, width: width, height: height)
}
我试过时间分析它,这是需要时间的输出。
基本上我只是显示与混合起来是绿色,红色或黄色像素的图片 – Recusiwe
你确定问题这里,而不是在创建'[PixelData取出]'数组的?在调试版本中,操作大型数组非常慢。如果您在开启优化功能的情况下进行版本构建,则使用大型数组要快得多。确保问题出现在这里,而不是创建该数组。然后,当然,确保当你在主队列中显示你正在做的图像时。 – Rob
@Recusiwe,您是否尝试过使用仪器来确定所有CPU的使用位置?你可以尝试从这个教程开始:https://www.raywenderlich.com/97886/instruments-tutorial-with-swift-getting-started –