iOS - 快速创建无符号字符
Posted
技术标签:
【中文标题】iOS - 快速创建无符号字符【英文标题】:iOS - create unsigned char in swift 【发布时间】:2017-05-23 23:27:56 【问题描述】:我正在将一些 Objective-C 代码转换为 Swift,其中包含以下代码:
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char rgba[4];
CGContextRef context = CGBitmapContextCreate(rgba, 1, 1, 8, 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGContextDrawImage(context, CGRectMake(0, 0, 1, 1), image.CGImage);
CGColorSpaceRelease(colorSpace);
CGContextRelease(context);
UIColor *averageColor = [UIColor colorWithRed:((CGFloat)rgba[0])/255.0 green:((CGFloat)rgba[1])/255.0 blue:((CGFloat)rgba[2])/255.0 alpha:alpha];
averageColor = [averageColor colorWithMinimumSaturation:0.15];
我已经设法轻松转换颜色空间,但如何在 Swift 3 中创建无符号字符?
我尝试了以下,但编译器提示以下错误:
Cannot convert value of type '[CUnsignedChar]' to expected argument type 'UnsafeMutableRawPointer?'
这是代码:
let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceRGB()
let rgba = [CUnsignedChar](repeating: 0,count: 4)
// error on this line because of the rgba
let context: CGContext = CGContext.init(data: rgba, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast | CGBitmapInfo.byteOrder32Big)
context.draw(image.cgImage!, in: CGRect(x: 0, y: 0, width: 1, height: 1))
我不能再继续下去了
有人可以帮忙吗?
谢谢
【问题讨论】:
【参考方案1】:试试这个..
let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceRGB()
let data = UnsafeMutableRawPointer.allocate(bytes: 4, alignedTo: 1) // 4 unsigned char = 4 bytes
let context: CGContext = CGContext.init(data: data, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast | CGBitmapInfo.byteOrder32Big)
let rgba = Array(UnsafeBufferPointer(start: data.assumingMemoryBound(to: UInt8.self), count: 4))
// .... other
【讨论】:
奇怪的是,这是我从***.com/a/29403023/1214800 翻译答案所需的确切代码?以上是关于iOS - 快速创建无符号字符的主要内容,如果未能解决你的问题,请参考以下文章