Rec*_*iwe 12 google-maps cgimage ios swift
在我的应用程序中,我正在创建一个图像映射浮动到像素值并将其用作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!)
}
Run Code Online (Sandbox Code Playgroud)
关于如何做这么长时间的任何建议?我可以看到它使用大约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)
}
Run Code Online (Sandbox Code Playgroud)
我试过时间分析它,这是需要时间的输出.
我尝试了你的代码,我发现问题不在于你的功能.
我认为你应该使用基于UInt8的像素结构而不是基于CGFloat的结构.
我翻译了你的代码用于cocoa应用程序,结果如下:
public struct PixelData {
var a: UInt8
var r: UInt8
var g: UInt8
var b: UInt8
}
func imageFromPixels(pixels: [PixelData], width: Int, 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,
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 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, g: 0, b: 0))
}
}
var ns = imageFromPixels(pixels: img, width: 20, height: 20)
Run Code Online (Sandbox Code Playgroud)
这段代码快速而轻巧,这是调试系统影响值:
我认为问题出现在加载像素数据的部分,检查它并确保它正常工作.
| 归档时间: |
|
| 查看次数: |
415 次 |
| 最近记录: |