admin管理员组文章数量:1291124
My camera will properly capture and display the image as you see it in the preview for smaller phone screens, such as the iPhone SE 2nd gen, but when doing the same on a larger screen, such as the iPhone 15, the captured image is squeezed together. For the larger screens, it's as if you are getting a wider view, and it gets horizontally squeezed together, with more extreme squeezing occurring in the middle of the screen.
The goal is to have the captured image display the image that was seen in the preview and captured, and it works well in most aspects, except for the larger screens squeezing once the image is captured.
The captured image will display properly in other views in the app after it's uploaded, as well as the database, leading me to believe the issue might come from the CameraView display. Changing the Image(uiImage: image) from .resizable to anything else hasn't worked, it just makes it worse, and no LLM model has been of help yet diagnosing where this issue stems from.
Why would you see varying results depending on the screen size, and how do you prevent that? I'm just trying to replicate a common camera, such as Snapchat or Instagram, and they've figured it out pretty well. Any help would be appreciated!
import SwiftUI
import AVFoundation
import Photos
struct CameraView: View {
@State private var capturedImage: UIImage? = nil
@Binding var selectedTab: Int
@ObservedObject var sharedData: SharedData
@State private var showUploadPostView = false
@State private var showingCameraSettingsAlert = false
@State private var showSaveAlert = false
@State private var saveAlertMessage = ""
@State private var showSettingsAlert = false
var body: some View {
ZStack {
if AVCaptureDevice.authorizationStatus(for: .video) == .authorized ||
AVCaptureDevice.authorizationStatus(for: .video) == .notDetermined {
if let image = capturedImage {
ZStack {
Image(uiImage: image)
.resizable()
.ignoresSafeArea()
// Top-left Save Button
VStack {
HStack {
Button(action: {
saveImage(image)
}, label: {
Image(systemName: "square.and.arrow.down")
.font(.system(size: 20))
.foregroundColor(.white)
.padding()
.background(Color.black.opacity(0.6))
.clipShape(Circle())
})
.padding(.top, 40)
.padding(.leading, 20)
Spacer()
}
Spacer()
}
// To position buttons
GeometryReader { geometry in
ZStack {
// Retake Button
Button(action: {
capturedImage = nil
sharedData.capturedImage = nil
}, label: {
Image(systemName: "goforward")
.font(.largeTitle)
.font(.system(size: 12))
.padding()
.background(Color.white)
.foregroundColor(.black)
.clipShape(Circle())
})
.scaleEffect(0.86)
.position(x: 50, y: geometry.size.height - 60)
// Upload Post Button
Button(action: {
sharedData.capturedImage = capturedImage
showUploadPostView = true
}, label: {
Image(systemName: "square.and.arrow.up")
.font(.largeTitle)
.font(.system(size: 12))
.padding()
.background(Color.white)
.foregroundColor(.black)
.clipShape(Circle())
})
.scaleEffect(0.86)
.position(x: geometry.size.width - 50, y: geometry.size.height - 60)
}
}
}
.alert(isPresented: $showSaveAlert) {
if showSettingsAlert {
// Alert with two buttons: "Settings" and "OK"
return Alert(
title: Text("Save Image"),
message: Text(saveAlertMessage),
primaryButton: .default(Text("Settings"), action: {
// Open app settings
if let appSettings = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(appSettings)
}
}),
secondaryButton: .cancel(Text("OK"))
)
} else {
// Alert with a single "OK" button
return Alert(
title: Text("Save Image"),
message: Text(saveAlertMessage),
dismissButton: .default(Text("OK"))
)
}
}
} else {
CustomCameraView(capturedImage: $capturedImage)
}
} else {
// Camera access denied view
VStack {
Text("Camera Access Denied")
.font(.title)
.padding()
Text("Please enable camera access in Settings to use this feature.")
.multilineTextAlignment(.center)
.padding()
Button("Open Settings") {
UIApplication.shared.open(
URL(string: UIApplication.openSettingsURLString)!,
options: [:],
completionHandler: nil
)
}
.padding()
.foregroundColor(.white)
.background(Color.blue)
.clipShape(RoundedRectangle(cornerRadius: 10))
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.gray.opacity(0.3))
.onAppear {
showingCameraSettingsAlert = true
}
}
}
.fullScreenCover(isPresented: $showUploadPostView) {
UploadPostView(
selectedTab: $selectedTab,
sharedData: sharedData
) {
// Reset captured image after successful upload
capturedImage = nil
sharedData.capturedImage = nil
}
}
}
// Save Image and Error Handling
func saveImage(_ image: UIImage) {
let photoAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
switch photoAuthorizationStatus {
case .authorized:
// Save the image
let imageSaver = ImageSaver()
imageSaver.successHandler = {
saveAlertMessage = "Your image has been saved to the photo gallery."
showSaveAlert = true
showSettingsAlert = false
}
imageSaver.errorHandler = { error in
saveAlertMessage = "Failed to save image: \(error.localizedDescription)"
showSaveAlert = true
showSettingsAlert = false
}
imageSaver.saveImageToPhotoAlbum(image: image)
case .denied, .restricted:
// Show alert guiding user to Settings
saveAlertMessage = "Photo library access is denied. Please enable it in Settings to save images."
showSaveAlert = true
showSettingsAlert = true
case .notDetermined:
// Request permission
PHPhotoLibrary.requestAuthorization { status in
if status == .authorized {
saveImage(image)
} else {
saveAlertMessage = "Photo library access is denied. Please enable it in Settings to save images."
showSaveAlert = true
showSettingsAlert = true
}
}
case .limited:
// Handle limited access if needed
saveAlertMessage = "Photo library access is limited. The image might not be saved properly."
showSaveAlert = true
showSettingsAlert = false
// Proceed to save the image
let imageSaver = ImageSaver()
imageSaver.successHandler = {
saveAlertMessage = "Your image has been saved to the photo gallery."
showSaveAlert = true
showSettingsAlert = false
}
imageSaver.errorHandler = { error in
saveAlertMessage = "Failed to save image: \(error.localizedDescription)"
showSaveAlert = true
showSettingsAlert = false
}
imageSaver.saveImageToPhotoAlbum(image: image)
@unknown default:
saveAlertMessage = "An unknown error occurred."
showSaveAlert = true
showSettingsAlert = false
}
}
}
import SwiftUI
struct CustomCameraView: View {
@StateObject var cameraService = CameraService()
@Binding var capturedImage: UIImage?
@Environment(\.presentationMode) private var presentationMode
var body: some View {
ZStack {
CamView(cameraService: cameraService) { result in
switch result {
case .success(let image):
capturedImage = image
presentationMode.wrappedValue.dismiss()
case .failure(let err):
print(err.localizedDescription)
}
}
.edgesIgnoringSafeArea(.all)
VStack {
HStack {
Spacer()
Button(action: {
cameraService.toggleFlash()
}) {
Image(systemName: cameraService.flashMode == .on ? "bolt.fill" : "bolt.slash.fill")
.font(.system(size: 20))
.foregroundColor(.white)
.padding()
.background(Color.black.opacity(0.6))
.clipShape(Circle())
}
.padding(.top, 40)
.padding(.trailing, 20)
}
Spacer()
GeometryReader { geometry in
ZStack {
Button(action: {
cameraService.capturePhoto()
}) {
Image(systemName: "circle")
.font(.system(size: 72))
.foregroundStyle(.white)
}
.position(x: geometry.size.width / 2, y: geometry.size.height - 100)
Button(action: {
cameraService.toggleCamera()
}) {
Image(systemName: "camera.rotate")
.font(.system(size: 24))
.padding()
.background(Color.white)
.foregroundColor(.black)
.clipShape(Circle())
}
.position(x: geometry.size.width - 50, y: geometry.size.height - 100)
}
}
.frame(height: 100)
}
.padding(.bottom, -40)
}
}
}
本文标签: iosSwiftUICaptured Image is Different From Camera PreviewStack Overflow
版权声明:本文标题:ios - SwiftUI - Captured Image is Different From Camera Preview - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741525727a2383452.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论