我尝试使用以下代码从OpenGL保存位图图像(UIImage):
func savePixels(x: Int, y: Int, w: Int, h: Int) -> UIImage {
let bitsPerComponent:Int = 8
let bitsPerPixel:Int = 32
let byteLength = Int(w * h) * 4;
let bytes = UnsafeMutablePointer<GLubyte>.allocate(capacity: byteLength)
bytes.initialize(to: GLubyte())
glReadPixels(0, 0, GLsizei(w), GLsizei(h), GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), bytes)
for i in 0 ..< Int(w * h) {
let r = bytes[4 * i + 0]
let g = bytes[4 * i + 1]
let b = bytes[4 * i + 2]
let a = bytes[4 * i + 3]
bytes[4 * i ] = b
bytes[4 * i + 1] = g
bytes[4 * i + 2] = r
bytes[4 * i + 3] = a
}
let dataProvider = CGDataProvider(dataInfo: nil, data: bytes, size: byteLength, releaseData: { (info, data, size) -> Void in
//data.deallocate(bytes: size, alignedTo: MemoryLayout<GLubyte>.alignment)
})
let colorspace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.first.rawValue)
let aCGImage = CGImage(
width: Int(w),
height: Int(h),
bitsPerComponent: bitsPerComponent,
bitsPerPixel: bitsPerPixel,
bytesPerRow: Int(w) * 4,
space: colorspace,
bitmapInfo: bitmapInfo,
provider: dataProvider!,
decode: nil,
shouldInterpolate: false,
intent: .defaultIntent
)!
return UIImage.init(cgImage: aCGImage, scale: 1, orientation: .up)
}
,但是我得到的图像带有白色背景,但是我想得到具有透明背景的图像!我该怎么办?请帮助!