Created
January 24, 2023 21:23
-
-
Save lanserxt/de1b958a86aa1de5b45c9975724a9d83 to your computer and use it in GitHub Desktop.
GradientColorPicker+SwiftUI
This file contains hidden or 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
struct ColorSliderView: View { | |
//Picked Color | |
@State | |
private var location: CGPoint = CGPoint(x: 0, y: 0) { | |
didSet { | |
//Need https://gist.githubusercontent.com/marchinram/3675efc96bf1cc2c02a5/raw/ec95113fa3cf1a6e97361426dc7574d9e14a09c0/UIImage+PixelColor.swift | |
currentColor = trackImage[Int(location.x), 0] ?? .white | |
} | |
} | |
@State | |
private var currentColor: Color = .red | |
@State | |
private var totalWidth: CGFloat = 0.0 | |
@State | |
private var trackImage: UIImage = UIImage() | |
var body: some View { | |
VStack { | |
Text("Color picker") | |
Image(uiImage: trackImage) | |
//.resizable() | |
.frame(height: 24) | |
GeometryReader { geo in | |
ZStack { | |
trackRect | |
Circle() | |
.stroke(style: StrokeStyle.init(lineWidth: 6.0)) | |
.frame(width: 48, height: 48) | |
.background(currentColor) | |
.cornerRadius(48.0 / 2.0) | |
.clipped() | |
.position(CGPoint(x: location.x, y: geo.frame(in: .local).midY)) | |
.gesture( | |
simpleDrag | |
) | |
}.onAppear { | |
totalWidth = geo.size.width | |
if #available(iOS 16.0, *) { | |
let rendered = ImageRenderer(content: trackRect) | |
if let renderImg = rendered.uiImage { | |
trackImage = renderImg | |
print(trackImage.size) | |
} | |
location = CGPoint(x: geo.frame(in: .local).midX, | |
y: geo.frame(in: .local).midY) | |
} else { | |
// Fallback on earlier versions | |
} | |
} | |
} | |
} | |
} | |
private var trackRect: some View { | |
Rectangle() | |
.frame(width: totalWidth, height: 24) | |
.foregroundColor(.clear) | |
.background( | |
LinearGradient(gradient: Gradient(colors: [.red, .orange, .green, .cyan, .blue]), startPoint: .leading, endPoint: .trailing) | |
) | |
} | |
var simpleDrag: some Gesture { | |
DragGesture() | |
.onChanged { value in | |
self.location = CGPoint.init(x: value.location.x, y: 0) | |
} | |
} | |
} | |
struct ColorSliderView_Previews: PreviewProvider { | |
static var previews: some View { | |
ColorSliderView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment