How to get part of UnsafeMutableBufferPointer as new UnsafeMutableBufferPointer

I am playing around with image manipulation in swift.

Using this code to access image pixels.

Image pixels are indicated with UnsafeMutableBufferPointer

.

All pixels are in the same data list and each pixel location should be calculated with:

let index = y * rgba.width + x
let pixel = pixels[index]

      

I am trying to add subscript

like this for get

public subscript(index: Int) -> [Pixel] {
    get {
        var column = [Pixel]()
        for i in 0..<height {
            column.append(pixels[index*height + i])
        }

        return column
    }
}

      

So, is there a way to return UnsafeMutableBufferPointer

pointing to the right column? instead of an array?

I am trying to avoid more memory allocation.

thank

+3


source to share


1 answer


Like this?:



public subscript(rowIndex: Int) -> UnsafePointer<Pixel> {
  return pixels.baseAddress!.advanced(by: rowIndex * height)
}
public subscript(rowIndex: Int) -> UnsafeBufferPointer<Pixel> {
  return UnsafeBufferPointer(start: self[rowIndex], count: height)
}

      

0


source







All Articles