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

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

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

当前回答

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
    }
}

其他回答

struct AvatarImage: View {
    var body: some View {

            Image("myImage")
                .resizable()
                .scaledToFill() // <=== Saves aspect ratio
                .frame(width: 60.0, height:60)
                .clipShape(Circle())

    }
}

“图像属性”的定义如下:—

   Image("\(Image Name)")
   .resizable() // Let you resize the images
   .frame(width: 20, height: 20) // define frame size as required
   .background(RoundedRectangle(cornerRadius: 12) // Set round corners
   .foregroundColor(Color("darkGreen"))      // define foreground colour 

建议使用以下代码来匹配多个屏幕尺寸:

Image("dog")
    .resizable()
    .frame(minWidth: 200, idealWidth: 400, maxWidth: 600, minHeight: 100, idealHeight: 200, maxHeight: 300, alignment: .center)

为了使图像缩放到适合当前视图,我们使用resized()修饰符,它可以调整图像的大小以适应可用的空间。

例如:

 Image("ImageName")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: 200, height: 200, alignment: .center)

这是山景,这是我的照片。

让我们在代码中创建一个简单的图像视图。

var body: some View {
    Image(“mountains”)
}

结果看起来不太好。

让我们先调整它的大小,用一个刻度来适应它

var body: some View {
    Image(“mountains”)
        .resizable()
        .scaledToFit()
}

现在看起来好多了。

注意,这里有空白,因为图像是垂直拍摄的,而屏幕是水平的。

不使用尺寸来填充。

图像的某些部分超出了屏幕,但它看起来比默认的没有任何比例更好。

如果你点击预览里面的图片,你会看到图片有多大。蓝色的线是图像的边界。