微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift如何为图像定义内存? 继续出现错误:EXC_BAD_ACCESS

如何解决Swift如何为图像定义内存? 继续出现错误:EXC_BAD_ACCESS

我正在构建图像,然后尝试对其进行更新。该版本可以正常运行并显示正常,但是当我尝试对其进行更新时,我得到一个错误:线程1:EXC_BAD_ACCESS(code = 1,address = 0x105d14a44)与此:

self.pixelBuffer[pixelIndex] = .green

如果我注释掉该行,则图像在viewDidLoad中显示为原始构建(全蓝色)。

以下是详细信息:

在ViewController中:

var pixelBuffer : UnsafeMutablePointer<RGBA32>!

在viewDidLoad中:

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

然后循环访问100行和列:

        var pixelIndex = 1
        for row in 0..<self.rows {
            for i in 0..<self.cols {
            
                self.pixelBuffer[pixelIndex] = .blue  # This works fine
            
                pixelIndex += 1
            }
        }

然后在循环之后:

    let cgImage = miniImageContext!.makeImage()
    let miniImage = UIImage(cgImage: cgImage!)
    // display the image in the View
    miniImageView.image = miniImage

然后在viewWillAppear中循环播放,以更改蓝色图像,例如:

    guard var tiles = mapFile.tiles else {return}
    
    //MARK: Put mapFile tiles on Image
    for tile in tiles {
        let thisRow = tile.row
        let thisCol = tile.col

        var pixelIndex = 1
        if (thisRow! <= 1) {
            pixelIndex = 1 + (thisCol ?? 1)
        }
        else { //if (thisRow > 1) {
            pixelIndex = ((thisRow ?? 1) * self.cols) - (self.cols) + (thisCol ?? 1)
        }

        self.pixelBuffer[pixelIndex] = .green  # This produces the error

    }

我试图简化代码。例如,将其设置为.green的行将是一个切换案例,可根据tile变量中的属性将其设置为不同的颜色。

RGBA32是这样的:

struct RGBA32:等于{ 私人var颜色: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,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,alpha: 255)
static let brown = RGBA32(red: 127,green: 63,alpha: 255)

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。