【问题标题】:Create UIImage from RGBA data in swift快速从 RGBA 数据创建 UIImage
【发布时间】:2015-07-05 05:38:48
【问题描述】:

我有一个像素数组,需要从中创建 UIImage。像素数组对 RGBA 格式的每个像素使用 4 个字节。即 00000000 - 黑色透明,000000ff - 黑色不透明。

将使用 swift 和 xcode 6.3 或更高版本创建 UIImage。

需要遍历像素数组,每四个字节获取每个像素,并从像素中创建图像。

可以看到客观的 c 引用,但不清楚 swift 的代码示例。

【问题讨论】:

标签: ios swift rgba


【解决方案1】:

这是我用来从 RGBA 字节数组创建 CGImages 的示例:

struct m_RGBColor // My own data-type to hold the picture information
{
    var Alpha: UInt8 = 255
    var Red:   UInt8 = 0
    var Green: UInt8 = 0
    var Blue:  UInt8 = 0
}

var pixelArray: [m_RGBColor] = [m_RGBColor]()
var pixelColor: m_RGBColor = m_RGBColor()

for y in 0 ..< height // Height of your Pixture
{
    for x in 0 ..< width // Width of your Picture
    {
        onePixel.Alpha = 0 // Fill one Pixel with your Picture Data
        onePixel.Red   = 0 // Fill one Pixel with your Picture Data
        onePixel.Green = 0 // Fill one Pixel with your Picture Data
        onePixel.Blue  = 0 // Fill one Pixel with your Picture Data
        pixelArray.append(onePixel)
    }
}

let bitmapCount: Int = pixelArray.count
let elmentLength: Int = sizeof(m_RGBColor)
let render: CGColorRenderingIntent = CGColorRenderingIntent.RenderingIntentDefault
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo: CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue)
let providerRef: CGDataProvider? = CGDataProviderCreateWithCFData(NSData(bytes: &pixelArray, length: bitmapCount * elmentLength))
let cgimage: CGImage? = CGImageCreate(width, height, 8, 32, width * elmentLength, rgbColorSpace, bitmapInfo, providerRef, nil, true, render)
if cgimage != nil
{
    // You have success, the Image is valid and usable
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    相关资源
    最近更新 更多