我在Assets.xcassets中有一个大图像。如何用SwiftUI调整这张图片的大小使它变小?

我试着设置框架,但它不起作用:

Image(room.thumbnailImage)
    .frame(width: 32.0, height: 32.0)

当前回答

如果你想使用纵横比调整大小,那么你可以使用以下代码:

Image(landmark.imageName).resizable()
                .frame(width: 56.0, height: 56.0)
                .aspectRatio(CGSize(width:50, height: 50), contentMode: .fit)

其他回答

正如他们所说,你必须使用在SwiftUI上调整图像的大小:

调用一个图像-> image ("somename") 然后,添加-> . resized ()

现在图像可以调整大小了

接下来,你可以应用. aspectratio来适应尺寸或只是填充框架。

resized的简单用法示例:

Image("somename")
.resizable()
.frame(width: 50px, height: 50px) 

SwiftUI为我们提供了. resized()修饰符,它可以让SwiftUI调整图像的大小以适应其空间

struct ContentView: View {
    var body: some View {
        Image("home")
            .antialiased(true) //for smooth edges for scale to fill
            .resizable() // for resizing
            .scaledToFill() // for filling image on ImageView
    }
}

另一种方法是使用scaleEffect修饰符:

Image(room.thumbnailImage)
    .resizable()
    .scaleEffect(0.5)

您可以使用resized()属性,但请记住,您不能在普通修饰符中使用resized,因此您必须使用Image扩展来实现它。

extension Image {
    func customModifier() -> some View {
        self
            .resizable()
            .aspectRatio(contentMode: .fit)
    }

如果你想使用纵横比调整大小,那么你可以使用以下代码:

Image(landmark.imageName).resizable()
                .frame(width: 56.0, height: 56.0)
                .aspectRatio(CGSize(width:50, height: 50), contentMode: .fit)