Swift 自我形象的创造与改变

Swift self image creation and change

在 Swift 中我有一个图像:(但{我认为}问题是 'self' 是如何实现的) (在我看来DidLoad)

let colorSpace       = CGColorSpaceCreateDeviceRGB()
let bytesPerPixel    = 4
let bitsPerComponent = 8
let bytesPerRow      = bytesPerPixel * self.cols // width
let bitmapInfo       = RGBA32.bitmapInfo
let minimapContext = CGContext(data: nil, width: self.cols, height: self.rows, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo)
let buffer = minimapContext!.data
self.pixelBuffer = buffer!.bindMemory(to: RGBA32.self, capacity: self.cols * self.rows) // was let

var pixelIndex = 1

然后我遍历一个类似的数组:

self.pixelBuffer[pixelIndex] = .blue

没有 'self' 一切正常。

我想更改一些像素,所以我添加了 'self' 并将其定义在 ViewController class

的顶部

现在像这样更改像素:

self.pixelBuffer[newPixelIndex] = .lightblue

但是我遇到了各种错误: 无法将类型 'UnsafeMutablePointer' 的值分配给类型 'RGBA32'

无法推断参考成员的上下文基础 'lightblue'

'RGBA32?' 类型的值没有下标

不知道这是否有帮助,但 pixelBuffer 的定义如下:

var pixelBuffer: RGBA32? = nil

这里是 RGBA32:

struct RGBA32: Equatable {
private var color: UInt32

init(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8) {
    color = (UInt32(red) << 24) | (UInt32(green) << 16) | (UInt32(blue) << 8) | (UInt32(alpha) << 0)
}

static let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Little.rawValue

static func ==(lhs: RGBA32, rhs: RGBA32) -> Bool {
    return lhs.color == rhs.color
}

static let black = RGBA32(red: 0, green: 0, blue: 0, alpha: 255)
static let red   = RGBA32(red: 255, green: 0, blue: 0, alpha: 255)
static let green = RGBA32(red: 24, green: 183, blue: 3, alpha: 255)
static let darkgreen = RGBA32(red: 70, green: 105, blue: 35, alpha: 255)
static let blue  = RGBA32(red: 0, green: 127, blue: 255, alpha: 255)
static let lightblue = RGBA32(red: 33, green: 255, blue: 255, alpha: 255)
static let brown = RGBA32(red: 127, green: 63, blue: 0, alpha: 255)

}

谢谢!!

主要问题是您已将 self.pixelBuffer 声明为可选 RGBA32。但这不是 pixelBuffer 之前的样子。这是一个 UnsafeMutablePointer<RGBA32>。这是您需要的声明:

var pixelBuffer : UnsafeMutablePointer<RGBA32>!

我想你所有的问题都会消失。你的

self.pixelBuffer[newPixelIndex] = .lightblue

然后为我编译。