尝试从随机生成的原始像素创建位图图像

时间:2019-11-02 23:55:17

标签: ios swift bitmap core-graphics

我试图更好地了解如何使用Core Graphics和CGImage.init将位图像素绘制到iOS屏幕。我从随机生成的颜色(静态)开始。如何正确执行此操作?

此代码基于an example created by Human Friendly

import UIKit
import CoreGraphics

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    public struct PixelData {
        var a:UInt8 = 255
        var r:UInt8
        var g:UInt8
        var b:UInt8
    }

    private let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
    private let bitmapInfo:CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)

    public func imageFromARGB32Bitmap(pixels:[PixelData], width:Int, height:Int)->UIImage {
        let bitsPerComponent:Int = 8
        let bitsPerPixel:Int = 32

        assert(pixels.count == width * height)

        var data = pixels

        let providerRef = CGDataProvider(
            data: NSData(
                bytes: &data,
                length: data.count * MemoryLayout.size(ofValue: data[0])))

        let cgim = CGImage.init(
            width: width,
            height: width,
            bitsPerComponent: bitsPerComponent,
            bitsPerPixel: bitsPerComponent,
            bytesPerRow:  width * MemoryLayout.size(ofValue: PixelData.self),
            space: rgbColorSpace,
            bitmapInfo: bitmapInfo,
            provider: providerRef!,
            decode: nil,
            shouldInterpolate: true,
            intent: CGColorRenderingIntent.defaultIntent)!

        return UIImage(cgImage: cgim)
    }


    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func redraw(_ sender: Any) {
        let pixels = randomStatic(512, 512)
        imageView.image = imageFromARGB32Bitmap(pixels: pixels, width: 512, height: 512)
    }

    func randomStatic(_ width: Int, _ height: Int) -> [PixelData] {

        var pixelData: [PixelData] = []

        for row in 0..<height {
            for column in 0..<width {
                pixelData.append(PixelData.init(
                    r: UInt8.random(in: 0...255),
                    g: UInt8.random(in: 0...255),
                    b: UInt8.random(in: 0...255)))
            }
        }

        return pixelData
    }
}

在CGImage.init的最后一行中,我得到“在展开可选值时意外发现nil。”

0 个答案:

没有答案