I am doing some tests where someone can select an image from their photo gallery . Once they select an image there will be a text in the center of the image "Sample test" I want that text to be draggable within the bounds of the image selected . I have everything working except getting the correct bounds of the image . I am able to drag that test outside of the image frame . I am getting the frame of the image in the PhotosPicker . Does anyone know how I can get the correct frame of image selected
import SwiftUI
import PhotosUI
struct TextView: View {
@State var viewState = CGVector(dx: 0, dy: 0)
@State var textProxy = CGSize.zero
@Binding var width: CGFloat
@Binding var height: CGFloat
var body: some View {
VStack {
ZStack {
Text("Sample test")
.foregroundColor(.black)
.font(.system(size: 20))
.foregroundColor(.red)
.font(.system(size: 15))
.offset(x: viewState.dx, y: viewState.dy)
.gesture(
DragGesture()
.onChanged { value in
if value.translation.width < (width/2 - textProxy.width/2) && value.translation.width + (width/2 - textProxy.width/2) > 0 {
viewState.dx = value.translation.width
}
if value.translation.height < (height/2 - textProxy.height/2) && value.translation.height + (height/2 - textProxy.height/2) > 0 {
viewState.dy = value.translation.height
}
}
)
.background {
GeometryReader { proxy in
Color.clear
.onAppear {
textProxy = proxy.size
}
}
}
}
}
}
}
struct DragView: View {
@State var MediaType = "Image"
@State private var selectedItem: [PhotosPickerItem] = []
@State var ImageUpload: UIImage?
@State var width: CGFloat = 0.0
@State var height: CGFloat = 0.0
@State private var mediaData: Data?
var body: some View {
VStack {
if let data = mediaData, let uiimage = UIImage(data: data) {
ZStack {
GeometryReader { geo in
Image(uiImage: uiimage)
.resizable()
.aspectRatio(contentMode: .fit)
.padding(.top, 10)
.overlay(
TextView(width: $width, height: $height), alignment: .center)
.onAppear(){
print("geo height \(geo.size.height)")
}
}
}
}
PhotosPickerComponents
}
}
var PhotosPickerComponents: some View {
PhotosPicker(selection: $selectedItem,
maxSelectionCount: 1,
matching: .any(of: [.images, .videos])) {
Image(systemName: "photo")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 24, height: 24)
.foregroundColor(.black)
.padding(.leading, 30)
}.onChange(of: selectedItem) { newMedia in
DispatchQueue.main.async {
guard let item = selectedItem.first else {
return
}
item.loadTransferable(type: Data.self) { result in
switch result {
case .success(let data):
if let data = data {
self.mediaData = data
ImageUpload = UIImage(data: data)
width = ImageUpload?.size.width ?? 0
height = ImageUpload?.size.height ?? 0
print(height)
} else {
print("data is nil")
}
case .failure(let failure):
fatalError("\(failure)")
}
}
}
}
}
}
struct DragView_Previews: PreviewProvider {
static var previews: some View {
DragView()
}
}