Created
June 17, 2021 12:17
-
-
Save OskarGroth/960e20e73e0a45a536403fe063bd5a0b to your computer and use it in GitHub Desktop.
AppleLogo.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ContentView.swift | |
// AppleLogo | |
// | |
// Created by Oskar Groth on 2021-06-17. | |
// | |
import SwiftUI | |
struct ContentView: View { | |
static let colors = [Color.green, .yellow, .orange, .red, .purple, .blue] | |
var body: some View { | |
Canvas { context, size in | |
let image = context.resolve(Image(systemName: "applelogo")) | |
let ratio = min(size.width / image.size.width, size.height / image.size.height) | |
let drawSize = CGSize(width: image.size.width * ratio, height: image.size.height * ratio) | |
let height = size.height/CGFloat(Self.colors.count + 2) | |
context.clipToLayer(content: { innerContext in | |
innerContext.draw(image, in: .init(origin: .init(x: (size.width - drawSize.width)/2, y: -2), size: drawSize)) | |
}) | |
for (index, color) in Self.colors.enumerated() { | |
context.fill( | |
Path( | |
CGRect(origin: .init(x: 0, y: index == 0 ? 0 : Int(height) * (2 + index)), | |
size: .init(width: size.width, height: index == 0 ? height * 3 : height)) | |
), with: .color(color) | |
) | |
} | |
} | |
.frame(width: 128, height: 128) | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For more optimizing: move the .green color special case out of the loop to avoid extra conditional code inside the loop: