Skip to content

Instantly share code, notes, and snippets.

@CodeSlicing
Last active January 25, 2020 19:43
Show Gist options
  • Save CodeSlicing/c4d59618d66117a502c8ed8dcfb98c4b to your computer and use it in GitHub Desktop.
Save CodeSlicing/c4d59618d66117a502c8ed8dcfb98c4b to your computer and use it in GitHub Desktop.
Example of how GradientMap can be used to control the color of a view dependent on its size
//
// ColorBasedOnSizeDemo.swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
// AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Created by Adam Fordyce on 24/01/2020.
// Copyright © 2020 Adam Fordyce. All rights reserved.
//
import SwiftUI
import PureSwiftUITools
private let gradientMap = GradientMap([.pureYellow, .pureRed], withResolution: 50)
struct ColorBasedOnSizeDemo: View {
@State private var toggle = false
var body: some View {
VStack(spacing: 5) {
ForEach(0..<30) { index in
ColorBand(trigger: self.toggle)
}
}
.onAppear {
every (1) { timer in
withAnimation(Animation.easeInOut(duration: 2)) {
self.toggle.toggle()
}
}
}
}
}
private struct ColorBand: View {
let trigger: Bool
var body: some View {
let randomValue = 1.0.random()
return Rectangle()
.fillColor(gradientMap.colorAt(randomValue))
.height(4 + randomValue * 150)
.greedyWidth()
}
}
struct ColorBasedOnSizeDemo_Previews: PreviewProvider {
struct ColorBasedOnSizeDemo_Harness: View {
var body: some View {
ColorBasedOnSizeDemo()
}
}
static var previews: some View {
ColorBasedOnSizeDemo_Harness()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment