Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

528
Views
¿Por qué el archivo .png que exporto desde View (SwiftUI) no contiene ImageView?

Mientras uso Image("my file url") en mi CoverImageView , puedo exportar un archivo .png que contiene la vista Image("my file url") con éxito. Sin embargo, esto no sucede cuando uso Image(nsImage: NSImage(data: imageData.imagedata)) , imageData.imagedata es un tipo de datos que se obtendrá cuando toque un botón y lo obtenga de una imagen seleccionada (I lo mostraré más adelante en mi código).

Cuando selecciono una imagen, se puede ver en la Vista de mi aplicación:

La imagen contiene vista de Mac

Sin embargo, cuando guardo esta vista ( CoverImageView ) en un archivo .png, solo contiene la vista azul, ¡la vista de Mac desaparece!

Aquí está el CoverImageView desde el que quiero crear un archivo .png

 struct CoverImageView: View { @EnvironmentObject var imageData: ImageData var body: some View { ZStack { Rectangle() .frame(width: 512, height: 600) .foregroundColor(.blue) Image(nsImage: (NSImage(data: imageData.imagedata) ?? NSImage(byReferencing: URL(fileURLWithPath: "")))) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 512, height: 512) } } }

Esta es la vista principal PhotoTestView

 struct PhotoTestView: View { @State private var imageUrl: URL = URL(fileURLWithPath: "") @EnvironmentObject var imageData: ImageData var body: some View { VStack { CoverImageView() Divider() .frame(width: 1024) HStack { Button(action: { if let openURL = ImageProcess().showOpenPanel() { imageUrl = openURL if let codedImages = try? Data(contentsOf: openURL) { imageData.imagedata = codedImages } } }, label: { Image(systemName: "doc.badge.plus") }) Button(action: { ImageProcess().saveImage() }, label: { Image(systemName: "square.and.arrow.down") }) }.padding() } } }

La extensión de vista

 extension View { func imageRepresentation(rect: CGRect) -> NSBitmapImageRep? { let hosting = NSHostingView(rootView: self) hosting.setFrameSize(rect.size) hosting.setBoundsSize(rect.size) hosting.layout() hosting.layerContentsRedrawPolicy = .onSetNeedsDisplay hosting.setNeedsDisplay(rect) if let imageRepresentation = hosting.bitmapImageRepForCachingDisplay(in: rect) { hosting.cacheDisplay(in: rect, to: imageRepresentation) return imageRepresentation } return nil } func asImage(rect: CGRect) -> NSImage? { if let cgImage = imageRepresentation(rect: rect)?.cgImage { return NSImage(cgImage: cgImage, size: rect.size) } return nil } func asPngData(rect: CGRect) -> Data? { return imageRepresentation(rect: rect)?.representation(using: .png, properties: [:]) } }

Lector de archivos .png y Guardar

 struct ImageProcess { func showOpenPanel() -> URL? { let openPanel = NSOpenPanel() openPanel.allowedContentTypes = [.image] openPanel.allowsMultipleSelection = false openPanel.canChooseDirectories = false openPanel.canChooseFiles = true let response = openPanel.runModal() return response == .OK ? openPanel.url : nil } func saveURL() -> URL? { let savePanel = NSSavePanel() savePanel.allowedContentTypes = [.png] savePanel.canCreateDirectories = true savePanel.isExtensionHidden = false savePanel.allowsOtherFileTypes = false savePanel.title = "Save your image" savePanel.message = "Choose a folder and a name to store your image." savePanel.nameFieldLabel = "File name:" let response = savePanel.runModal() return response == .OK ? savePanel.url : nil } func saveImage() { let view = CoverImageView().environmentObject(ImageData()) let imageData = view.asPngData(rect: CGRect.init(x: 0, y: 0, width: 1024, height: 768)) if let url = saveURL() { try? imageData!.write(to: url) } // print(imageData) } }

El código completo se puede ver en Github

Por favor, ayúdame....

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!