在我的应用程序中,我创建一个映像映射漂移到像素值,并将其用作Google地图上的叠加层,但它永远要做,Android中的同样的事情几乎是即时的.我的代码如下所示:
- 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)
- }
我试图时间配置它,这是输出需要时间.
解决方法
我尝试了你的代码,我发现问题不在于你的功能.
我认为你应该使用基于UInt8的像素结构,而不是基于CGFloat的结构.
我翻译了可可应用程序的代码,结果是:
- public struct PixelData {
- var a: UInt8
- var r: UInt8
- var g: UInt8
- var b: UInt8
- }
- func imageFromPixels(pixels: [PixelData],height: Int) -> NSImage? {
- 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,intent: .defaultIntent
- )
- if cgimage == nil {
- print("CGImage is not supposed to be nil")
- return nil
- }
- return NSImage(cgImage: cgimage!,size: NSSize(width: width,height: height))
- }
- var img = [PixelData]()
- for i: UInt8 in 0 ..< 20 {
- for j: UInt8 in 0 ..< 20 {
- // Creating a red 20x20 image.
- img.append(PixelData(a: 255,r: 255,b: 0))
- }
- }
- var ns = imageFromPixels(pixels: img,width: 20,height: 20)
我认为问题出现在加载像素数据的部分,检查它并确保它正常工作.