ios - SwiftUI 中的前后图像滑块?
问题描述
我试图在 SwiftUI 中找到图像的前后滑块效果。但我找不到任何库或解决方案。最后我自己想出了以下解决方案。
希望这对某人有帮助!
解决方案
我已经为图像添加了背景颜色,以便在没有图像的情况下有所不同。
import SwiftUI
struct ContentView: View {
@State private var location: CGPoint = CGPoint(x: 0, y: 0)
@State private var maskWidth: CGFloat = 0.0
@State var startPoint: CGFloat = 0
@State var endPoint: CGFloat = 0
@State var yPoint: CGFloat = 0
var sliderWidth: CGFloat = 30
var containerWidth: CGFloat = 400
var containerHeight: CGFloat = 300
var body: some View {
ZStack {
ZStack() {
Image("before_img")
.resizable()
.frame(width: containerWidth, height: containerHeight)
.background(Color.red)
.clipped()
Image("after_img")
.resizable()
.frame(width: containerWidth, height: containerHeight)
.clipped()
.background(Color.green)
.mask(mask)
}
.clipped()
Slider
}
.clipped()
.frame(width: containerWidth, height: containerHeight)
.onAppear {
yPoint = containerHeight/2
location = CGPoint(x: containerWidth/2, y: yPoint)
maskWidth = containerWidth/2
endPoint = containerWidth
}
}
var dragAction: some Gesture {
DragGesture()
.onChanged { value in
updateDragView(point: value.location)
updateMaskView(point: value.translation)
}
.onEnded { value in
setInitialPosition()
}
}
var mask: some View {
HStack {
Spacer()
Rectangle()
.mask(Color.black)
.frame(width: maskWidth, height: containerHeight)
}
}
var Slider: some View {
VStack(spacing: 0) {
Rectangle()
.fill(Color.white)
.frame(width: 4)
Image(systemName: "circle.circle.fill")
.foregroundColor(.white)
.frame(width: sliderWidth, height: sliderWidth)
.font(.system(size: sliderWidth))
Rectangle()
.fill(Color.white)
.frame(width: 4)
}
.position(location)
.gesture(dragAction)
.shadow(radius: 4)
}
func updateDragView(point: CGPoint) {
let locX = point.x
if locX > startPoint && locX < endPoint {
self.location = CGPoint(x: point.x, y: yPoint)
}
}
func updateMaskView(point: CGSize) {
let width = -(point.width)
let newWidth = ((containerWidth/2)+width)
if newWidth > 0 {
maskWidth = ((containerWidth/2)+width)
} else {
setInitialPosition()
}
}
func setInitialPosition() {
withAnimation {
location = CGPoint(x: containerWidth/2, y: yPoint)
maskWidth = containerWidth/2
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
推荐阅读
- c# - 定时器只执行几次
- html - 使用 Bootstrap - 如何使 2 行,每行有两个水平列,具有相同的高度,同时保持响应
- javascript - 如何使用 reactjs 验证对象数组
- javascript - 打开模式时Javascript触发的CSS转换失败
- android - Google Play Billing(测试模式):为什么我的购买会被自动取消
- vba - 我想知道如何使用表单按钮将记录保存到表中并在保存时打开一个新表单
- java - 我正在尝试使用 selenium 在自动化测试下执行我的 maven 项目
- sql - 加入日期相同或过去的第一个 id
- java - RestTemplate 交换超时但 PostMan 工作
- gnuplot - 如何在 gnu multiplot 中管理刻度标签和轴标签