Skip to content

Commit

Permalink
Extend Rgba with initializer from array, array slice, buffer and buff…
Browse files Browse the repository at this point in the history
…er slice
  • Loading branch information
valeriyvan committed Apr 28, 2024
1 parent fb07aec commit e931f9d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
4 changes: 2 additions & 2 deletions Sources/geometrize/Bitmap.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public struct Bitmap {
for y in 0..<height {
for x in 0..<width {
let offset = (width * y + x) * 4
let rgba = Rgba(r: data[offset + 0], g: data[offset + 1], b: data[offset + 2], a: data[offset + 3]).blending(background: background)
let rgba = Rgba(data[offset..<offset+4]).blending(background: background)
buffer[offset + 0] = rgba.r
buffer[offset + 1] = rgba.g
buffer[offset + 2] = rgba.b
Expand Down Expand Up @@ -132,7 +132,7 @@ public struct Bitmap {
get {
backing.withUnsafeBufferPointer {
let offset = offset(x: x, y: y)
return Rgba(r: $0[offset], g: $0[offset + 1], b: $0[offset + 2], a: $0[offset + 3])
return Rgba($0[offset..<offset + 4])
}
}
set {
Expand Down
32 changes: 32 additions & 0 deletions Sources/geometrize/Rgba.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,38 @@ public struct Rgba {
self.a = a
}

public init(_ array: [UInt8]) {
assert(array.count == 4)
self.r = array[0]
self.g = array[1]
self.b = array[2]
self.a = array[3]
}

public init(_ slice: ArraySlice<UInt8>) {
assert(slice.count == 4)
self.r = slice[slice.startIndex]
self.g = slice[slice.startIndex + 1]
self.b = slice[slice.startIndex + 2]
self.a = slice[slice.startIndex + 3]
}

public init(_ buffer: UnsafeBufferPointer<UInt8>) {
assert(buffer.count == 4)
self.r = buffer[0]
self.g = buffer[1]
self.b = buffer[2]
self.a = buffer[3]
}

public init(_ slice: Slice<UnsafeBufferPointer<UInt8>>) {
assert(slice.count == 4)
self.r = slice[slice.startIndex]
self.g = slice[slice.startIndex + 1]
self.b = slice[slice.startIndex + 2]
self.a = slice[slice.startIndex + 3]
}

public func withAlphaComponent(_ alpha: UInt8) -> Rgba {
Rgba(r: r, g: g, b: b, a: alpha)
}
Expand Down

0 comments on commit e931f9d

Please sign in to comment.