尝试在 swiftUI 中调整 UIImage 的 UIViewRepresentable

Jus*_*808 5 swiftui

我有我的resize方法:

//
//  ImageView.swift
//  fairytales
//
//  Created by Justin Zaun on 7/12/20.
//  Copyright © 2020 JGZ. All rights reserved.
//

import SwiftUI

struct ImageView: UIViewRepresentable {
    
    var name: String
    
    fileprivate var imageView: UIImageView = UIImageView()
    fileprivate var originalImage: UIImage
    

    init(name: String) {
        self.name = name
        self.originalImage = UIImage(named: name)!
    }
    
    func makeUIView(context: Context) -> UIImageView {
        imageView.image = self.originalImage

        return imageView;
    }
    
    func updateUIView(_ uiView: UIImageView, context: Context) {
    }
    
    fileprivate func scaledImage(width: CGFloat, height: CGFloat) -> UIImage {
        let size = CGSize(width: width, height: height)
        if (self.originalImage.size == size) {
            return self.originalImage
        }
        
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        self.originalImage.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image!;
    }
    
    func resize(width: CGFloat, height: CGFloat) -> some View {
        self.imageView.image = scaledImage(width: width, height: height)
        print(self.imageView.image!.size)

        return self.frame(width: width, height: height)
    }
}
Run Code Online (Sandbox Code Playgroud)

在视图中,我尝试...

ImageView(name: "Letter-T")
    .resize(width: 100, height: 100)
Run Code Online (Sandbox Code Playgroud)

打印语句打印正确的尺寸,但屏幕上的图像没有调整大小。我究竟做错了什么?

小智 0

在 UIViewRepresentable 中,您应该使用绑定,因为 swiftui 通过绑定值更改重绘视图(在 updateUIView 中),并且 swiftui 在 UIViewRepresentable 中为 uikit 视图提供容器,这并不意味着 makeUIView 中返回的 uikit 视图将使其大小等于加载的图像大小提示:

struct SUIRemoteImage: View {
    @State private(set) var uiImage: UIImage?
    @Binding var url: String

    var body: some View {
        Group {
            if let image = uiImage {
                Image(uiImage: image)
                    .resizable()
            } else {
                Rectangle()
                    .foregroundColor(.white)
            }
        }
        .onAppear {
            loadImage()
        }
        .onChange(of: url) { _ in
            loadImage()
        }
    }
    
    private func loadImage() {
        //get img and attach data to uiImage (in main thread)
    }
}
Run Code Online (Sandbox Code Playgroud)