Skip to content

Instantly share code, notes, and snippets.

@nasdf
Created June 14, 2020 18:33
Show Gist options
  • Save nasdf/3e3f74a68cdff73f25f8e0dfa160e569 to your computer and use it in GitHub Desktop.
Save nasdf/3e3f74a68cdff73f25f8e0dfa160e569 to your computer and use it in GitHub Desktop.
Ethereum Blockies in SwiftUI
struct Blockies: View {
private var color: Color!
private var bgColor: Color!
private var spotColor: Color!
private var seed: [Int32] = Array(repeating: 0, count: 4)
private var pixels: [UInt8] = Array(repeating: 0, count: 100)
var body: some View {
VStack(alignment: .center, spacing: 0) {
ForEach(0..<10) { x in
HStack(alignment: .center, spacing: 0) {
ForEach(0..<10) { y in
self.pixel(x: x, y: y)
.frame(width: 20, height: 20)
}
}
}
}
}
init(data: Data) {
for (i, c) in data.enumerated() {
seed[i % 4] = (seed[i % 4] << 5) &- seed[i % 4] &+ Int32(c)
}
color = nextColor()
bgColor = nextColor()
spotColor = nextColor()
for x in 0..<10 {
for y in 0..<5 {
pixels[x * 10 + y] = UInt8(nextRand() * 2.3)
pixels[x * 10 + (9 - y)] = pixels[x * 10 + y]
}
}
}
private mutating func nextRand() -> Double {
let t = seed[0] ^ (seed[0] << 11)
seed[0] = seed[1]
seed[1] = seed[2]
seed[2] = seed[3]
seed[3] = seed[3] ^ (seed[3] >> 19) ^ t ^ (t >> 8)
let s = UInt32(bitPattern: seed[3])
return Double(s) / Double(1 << 31)
}
private mutating func nextColor() -> Color {
let h = nextRand()
let s = nextRand() * 0.6 + 0.4
let b = (nextRand() + nextRand() + nextRand() + nextRand()) / 2.0
return Color.init(hue: h, saturation: s, brightness: b)
}
private func pixel(x: Int, y: Int) -> some View {
switch pixels[x * 10 + y] {
case 0:
return Rectangle().fill(bgColor)
case 1:
return Rectangle().fill(color)
default:
return Rectangle().fill(spotColor)
}
}
}
struct Blockies_Previews: PreviewProvider {
static let data = "0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359".data(using: .utf8)!
static var previews: some View {
Blockies(data: data)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment