尝试在swiftUI中调整UIImage的UIViewRepresentable的大小

时间:2020-07-12 19:20:11

标签: 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)
    }
}

在视图中,我尝试...

ImageView(name: "Letter-T")
    .resize(width: 100, height: 100)

print语句将打印正确的尺寸,但是在屏幕上图像的尺寸未调整。我在做什么错了?

0 个答案:

没有答案