[英]Non-rectangular image cropping SwiftUI?
我想允許用戶通過在原始圖像上繪制閉合形狀來裁剪圖像。 有點像 Snapchat 貼紙。 我從 2012 年開始查看這篇文章,並且很好奇是否有更新的方法可以使用 SwiftUI 做到這一點。
為了澄清,我想在顯示的圖像上獲取用戶輸入(繪圖),並使用該形狀的蒙版裁剪實際圖像(而不是視圖)。
其實你的問題需要更具體。
但是您可以通過 swift ui 中的代碼來調整圖像大小。
Image("Your Image name here!")
.resizable()
.frame(width: 300, height: 300)
如果您想在圖像的任何 position 處進行裁剪,您可以試試這個
import SwiftUI
struct ContentView: View {
var body: some View {
CropImage(imageName: "Your Image name here!")
}
}
// struct Shape
struct CropFrame: Shape {
let isActive: Bool
func path(in rect: CGRect) -> Path {
guard isActive else { return Path(rect) } // full rect for non active
let size = CGSize(width: UIScreen.main.bounds.size.width*0.7, height: UIScreen.main.bounds.size.height/5)
let origin = CGPoint(x: rect.midX - size.width/2, y: rect.midY - size.height/2)
return Path(CGRect(origin: origin, size: size).integral)
}
}
// struct image crop
struct CropImage: View {
let imageName: String
@State private var currentPosition: CGSize = .zero
@State private var newPosition: CGSize = .zero
@State private var clipped = false
var body: some View {
VStack {
ZStack {
Image(imageName)
.resizable()
.scaledToFit()
.offset(x: currentPosition.width, y: currentPosition.height)
Rectangle()
.fill(Color.black.opacity(0.3))
.frame(width: UIScreen.main.bounds.size.width*0.7 , height: UIScreen.main.bounds.size.height/5)
.overlay(Rectangle().stroke(Color.white, lineWidth: 3))
}
.clipShape(
CropFrame(isActive: clipped)
)
.gesture(DragGesture()
.onChanged { value in
currentPosition = CGSize(width: value.translation.width + newPosition.width, height: value.translation.height + newPosition.height)
}
.onEnded { value in
currentPosition = CGSize(width: value.translation.width + newPosition.width, height: value.translation.height + newPosition.height)
newPosition = currentPosition
})
Button (action : { clipped.toggle() }) {
Text("Crop Image")
.padding(.all, 10)
.background(Color.blue)
.foregroundColor(.white)
.shadow(color: .gray, radius: 1)
.padding(.top, 50)
}
}
}
}
這是帶有圖像裁剪的視圖的完整代碼。
否則您可以使用 GitHub 中的庫,請參閱此處的 GitHub 演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.