转换为纹理时,缺少UIImage的透明度

时间:2018-09-05 10:38:38

标签: ios swift metal metalkit

我将UIImage转换为纹理,然后将其转换为UIImage。透明区域替换为黑色。

我用来将UIImage转换为纹理的函数。

func imageToTexture(imageNamed: String, device: MTLDevice) -> MTLTexture {
    let bytesPerPixel = 4
    let bitsPerComponent = 8

    var image = UIImage(named: imageNamed)!

    let width = Int(image.size.width)
    let height = Int(image.size.height)

    let bounds = CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))
    var rowBytes = width * bytesPerPixel
    var colorSpace = CGColorSpaceCreateDeviceRGB()

    let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: rowBytes, space: colorSpace, bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue).rawValue)

    context!.clear(bounds)
    context?.translateBy(x: CGFloat(width), y: CGFloat(height))
    //  CGContextTranslateCTM(context!, CGFloat(width), CGFloat(height))
    context?.scaleBy(x: -1.0, y: -1.0)
    //   CGContextScaleCTM(context!, -1.0, -1.0)
    context?.draw(image.cgImage!, in: bounds)
    //  CGContextDrawImage(context, bounds, image.CGImage)

    var texDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .bgra8Unorm , width: width, height: height, mipmapped: true)

    var texture = device.makeTexture(descriptor: texDescriptor)
    texture?.label = imageNamed

    // var pixelsData = CGBitmapContextGetData(context!)
    var pixelsData = context?.data
    var region = MTLRegionMake2D(0, 0, width, height)
    texture?.replace(region: region, mipmapLevel: 0, withBytes: pixelsData!, bytesPerRow: rowBytes)

    makeImage(from: texture!)
    return texture!
}

将纹理转换为UIImage的函数。将UIImage更改为纹理后,我要调用将其转换回UIImage。不是。

func makeImage(from texture: MTLTexture) -> UIImage? {
    let width = texture.width
    let height = texture.height
    let bytesPerRow = width * 4

    let data = UnsafeMutableRawPointer.allocate(bytes: bytesPerRow * height, alignedTo: 4)
    defer {
        data.deallocate(bytes: bytesPerRow * height, alignedTo: 4)
    }

    let region = MTLRegionMake2D(0, 0, width, height)
    texture.getBytes(data, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0)

    var buffer = vImage_Buffer(data: data, height: UInt(height), width: UInt(width), rowBytes: bytesPerRow)

    let map: [UInt8] = [2, 1, 0, 3]
    vImagePermuteChannels_ARGB8888(&buffer, &buffer, map, 0)

    guard let colorSpace = CGColorSpace(name: CGColorSpace.genericRGBLinear) else { return nil }
    guard let context = CGContext(data: data, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow,
                                  space: colorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { return nil }
    guard let cgImage = context.makeImage() else { return nil }

    let x =  UIImage(cgImage: cgImage)
    return x;
}

此处,输出图像在透明区域中为黑色。我不知道我搞砸了。

0 个答案:

没有答案