【发布时间】:2016-08-02 06:00:10
【问题描述】:
我使用this post 中引入的一种方法,针对 Swift 进行了修改:
func getRaster() -> [UIColor] {
let result = NSMutableArray()
let img = self.CGImage
let width = CGImageGetWidth(img)
let height = CGImageGetHeight(img)
let colorSpace = CGColorSpaceCreateDeviceRGB()
var rawData = [UInt8](count: width * height * 4, repeatedValue: 0)
let bytesPerPixel = 4
let bytesPerRow = bytesPerPixel * width
let bytesPerComponent = 8
let bitmapInfo = CGImageAlphaInfo.PremultipliedLast.rawValue | CGBitmapInfo.ByteOrder32Big.rawValue
let context = CGBitmapContextCreate(&rawData, width, height, bytesPerComponent, bytesPerRow, colorSpace, bitmapInfo)
CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), img);
for x in 0..<width {
for y in 0..<height {
let byteIndex = (bytesPerRow * x) + y * bytesPerPixel
let red = CGFloat(rawData[byteIndex] ) / 255.0
let green = CGFloat(rawData[byteIndex + 1]) / 255.0
let blue = CGFloat(rawData[byteIndex + 2]) / 255.0
let alpha = CGFloat(rawData[byteIndex + 3]) / 255.0
let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
result.addObject(color)
}
}
return (result as NSArray) as! [UIColor]
}
但问题是,只有当图像是正方形(即 32x32 精灵)时,它才会成功,每当我尝试获取尺寸不相等的图像“光栅”时,我都会得到“索引超出范围” " x = 16 和 y = 0 上 red 的致命错误(对于尺寸为 h:16,w:32 的图像)。有什么办法可以解决这个问题?
提前谢谢你!
【问题讨论】:
标签: ios swift core-graphics