简体   繁体   English

如何使用 SwiftUI 调整图像大小?

[英]How to resize Image with SwiftUI?

I have a large image in Assets.xcassets.我在 Assets.xcassets 中有一张大图。 How to resize this image with SwiftUI to make it small?如何使用 SwiftUI 调整此图像的大小以使其变小?

I tried to set frame but it doesn't work:我试图设置框架,但它不起作用:

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

You should use .resizable() before applying any size modifications on an Image .在对Image应用任何大小修改之前,您应该使用.resizable()

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

How about this:这个怎么样:

struct ResizedImage: View {
    var body: some View {
        Image("myImage")
            .resizable()
            .scaledToFit()
            .frame(width: 200, height: 200)
    }
}

The image view is 200x200, but the image maintains the original aspect ratio (rescaling within that frame).图像视图为 200x200,但图像保持原始纵横比(在该帧内重新缩放)。

In SwiftUI, use the .resizable() method to resize an image.在 SwiftUI 中,使用.resizable()方法来调整图像大小。 By using .aspectRatio() and specifying a ContentMode , you can either "Fit" or "Fill" the image, as appropriate.通过使用.aspectRatio()并指定ContentMode ,您可以根据需要“适合”或“填充”图像。

For example, here is code that resizes the image by fitting:例如,下面是通过拟合调整图像大小的代码:

Image("example-image")
.resizable()
.aspectRatio(contentMode: .fit)

Expanding on @rraphael's answer and comments:扩展@rraphael 的回答和评论:

As of Xcode 11 beta 2, you can scale an image to arbitrary dimensions, while maintaining the original aspect ratio by wrapping the image in another element.从 Xcode 11 beta 2 开始,您可以将图像缩放到任意尺寸,同时通过将图像包裹在另一个元素中来保持原始纵横比。

eg例如

struct FittedImage: View
{
    let imageName: String
    let width: CGFloat
    let height: CGFloat

    var body: some View {
        VStack {
            Image(systemName: imageName)
                .resizable()
                .aspectRatio(1, contentMode: .fit)
        }
        .frame(width: width, height: height)
    }
}


struct FittedImagesView: View
{
    private let _name = "checkmark"

    var body: some View {

        VStack {

            FittedImage(imageName: _name, width: 50, height: 50)
            .background(Color.yellow)

            FittedImage(imageName: _name, width: 100, height: 50)
            .background(Color.yellow)

            FittedImage(imageName: _name, width: 50, height: 100)
            .background(Color.yellow)

            FittedImage(imageName: _name, width: 100, height: 100)
            .background(Color.yellow)

        }
    }
}

Results结果

保持纵横比的拟合图像

(For some reason, the image is showing as a bit blurry. Rest assured that the real output is sharp.) (由于某种原因,图像显示有点模糊。请放心,实际输出很清晰。)

To render the image with a fit aspect ratio and clipping to bounds, use this code:要以合适的纵横比渲染图像并裁剪到边界,请使用以下代码:

struct ContentView: View {
    var body: some View {
        Image("donuts")
            .resizable()
            .scaledToFill()
            .frame(width: 200, height: 200)
            .border(Color.pink)
            .clipped()
    }
}

The result:结果:

在此处输入图像描述

You need to add the .resizable modifier, to be able to change the size of the image您需要添加.resizable修饰符,以便能够更改图像的大小

The code then would look like this:然后代码将如下所示:

Image(room.thumbnailImage)
    .resizable()
    .frame(width: 32.0, height: 32.0)
struct AvatarImage: View {
    var body: some View {

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

    }
}

Another approach is to use the scaleEffect modifier:另一种方法是使用scaleEffect修饰符:

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

Well, It's seems pretty easy in SwiftUI / Following the demo they given : https://developer.apple.com/videos/play/wwdc2019/204好吧,在SwiftUI似乎很容易/按照他们给出的演示: https ://developer.apple.com/videos/play/wwdc2019/204

struct RoomDetail: View {
     let room: Room
     var body: some View {

     Image(room.imageName)
       .resizable()
       .aspectRatio(contentMode: .fit)
 }

Hope it helps.希望能帮助到你。

Since we shouldn't hardcode/fix the image size.因为我们不应该硬编码/修复图像大小。 Here is a better way to provide range to adjust according to the screen's resolution on different devices.这是提供范围以根据不同设备上的屏幕分辨率进行调整的更好方法。

Image("ImageName Here")
       .resizable()
       .frame(minWidth: 60.0, idealWidth: 75.0, maxWidth: 95.0, minHeight: 80.0, idealHeight: 95.0, maxHeight: 110.0, alignment: .center)
       .scaledToFit()
       .clipShape(Capsule())
       .shadow(color: Color.black.opacity(5.0), radius: 5, x: 5, y: 5)

If you want to use aspect ratio with resizing then you can use following code:如果您想在调整大小时使用纵横比,则可以使用以下代码:

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

Note : My image name is img_Logo and you can change image name define image properties this:注意:我的图像名称是img_Logo ,您可以更改图像名称定义图像属性:

 VStack(alignment: .leading, spacing: 1) {
                        //Image Logo Start
                        Image("img_Logo")
                            .resizable()
                            .padding(.all, 10.0)
                            .frame(width: UIScreen.main.bounds.width * 0.4, height: UIScreen.main.bounds.height * 0.2)
                        //Image Logo Done
                    }

By default, image views automatically size themselves to their contents, which might make them go beyond the screen.默认情况下,图像视图会根据内容自动调整大小,这可能会使它们超出屏幕范围。 If you add the resizable() modifier then the image will instead automatically be sized so that it fills all the available space:如果添加 resizable() 修饰符,则图像将自动调整大小以填充所有可用空间:

Image("example-image")
    .resizable()

However, that may also cause the image to have its original aspect ratio distorted, because it will be stretched in all dimensions by whatever amount is needed to make it fill the space.但是,这也可能导致图像的原始纵横比失真,因为它会在所有维度上被拉伸到填充空间所需的任何量。

If you want to keep its aspect ratio you should add an aspectRatio modifier using either .fill or .fit, like this:如果要保持其纵横比,则应使用 .fill 或 .fit 添加 aspectRatio 修饰符,如下所示:

Image("example-image")
    .resizable()
    .aspectRatio(contentMode: .fit)

It is very important to understand logical structure of code.理解代码的逻辑结构非常重要。 Like in SwiftUI an image is not resizable by default.与 SwiftUI 一样,默认情况下图像不可调整大小。 Thus, to resize any image you have to make it resizable by applying the .resizable() modifier immediately after you declare an Image view.因此,要调整任何图像的大小,您必须在声明图像视图后立即应用 .resizable() 修饰符使其可调整大小。

Image("An Image file name")
    .resizable()

Use .resizable() method after image name.在图像名称后使用.resizable()方法。 Make sure usage of .resizable() need to declare before any modification.确保.resizable()的使用需要在任何修改之前声明。

like this:像这样:

Image("An Image file name")
    .resizable()
//add other modifications here 

To make an image scales to fit the current view, we use the resizable() modifier, which resizes an image to fit available space.为了使图像缩放以适应当前视图,我们使用 resizable() 修饰符,它调整图像大小以适应可用空间。

for Example:例如:

 Image("ImageName")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: 200, height: 200, alignment: .center)
Image(systemName: "person.fill")
  .font(.system(size: 13))

will also work if you are using systemName .如果您使用的是systemName ,也可以使用。

If you want to resize the image in swiftUI just use the following code :如果要在 swiftUI 中调整图像大小,只需使用以下代码:

import SwiftUI

    struct ImageViewer : View{
        var body : some View {
            Image("Ssss")
            .resizable()
            .frame(width:50,height:50)
        }
    }

But here is problem with this.但这是一个问题。 If you add this Image inside a Button, the Image will not be shown, just a block of blue colour would be there.如果将此图像添加到按钮中,则不会显示该图像,只会显示一个蓝色块。 To solve this issue, just do this :要解决此问题,只需执行以下操作:

import SwiftUI

struct ImageViewer : View{
    var body : some View {
        Button(action:{}){
        Image("Ssss")
        .renderingMode(.original)
        .resizable()
        .frame(width:50,height:50)
    }
   }
}

You can define Image Properties as follow:-您可以按如下方式定义图像属性:-

   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 

You can use resizable() property, but keep it in mind that you cannot use resizable in a common modifier so you have to use Image extension to achieve it.您可以使用resizable()属性,但请记住,您不能在通用修饰符中使用 resizable,因此您必须使用 Image 扩展来实现它。

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

It is suggested to use the following code to match multiple screen sizes:建议使用以下代码来匹配多种屏幕尺寸:

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

You also can use:您还可以使用:

Image("Example")
   .scaleEffect(NumberWithSizeBetweenZeroAndOne)

SwiftUI provided us .resizable() modifier that will let SwiftUI to resizes an image to fit its space SwiftUI 为我们提供了.resizable()修饰符,它可以让 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
    }
}

Here, it's a view of the mountains and this is my image.在这里,这是山景,这是我的形象。

在此处输入图像描述

Let's create a simple image view inside the code.让我们在代码中创建一个简单的图像视图。

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

在此处输入图像描述

The result doesn't look well.结果看起来不太好。

Let's resize it and use a scale to fit at first让我们调整它的大小并首先使用比例尺来适应

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

在此处输入图像描述

Now it looks much better.现在看起来好多了。

Notice that there is white space because the image is taken vertically and the screen is horizontal.请注意,由于图像是垂直拍摄的,而屏幕是水平的,因此存在空白。

Not use size to fill.不使用大小填充。

在此处输入图像描述

Some part of the image is beyond the screen but it looks better than the default without any scale.图像的某些部分超出了屏幕,但它看起来比没有任何比例的默认值更好。

If you click on the image inside Preview you'll see how big is the image.如果您单击预览中的图像,您将看到图像有多大。 That blue lines are the border of image.那条蓝线是图像的边界。

在此处输入图像描述

As they said you have to use for resizing an Image on SwiftUI :正如他们所说,您必须用于在 SwiftUI 上调整图像大小:

Call an image -> Image("somename") then, you add -> .resizable()调用图像 -> Image("somename")然后添加 -> .resizable()

and now the image is resizable现在图像可以调整大小

next you can apply .aspectRatio to fit dimension or just fill the frame.接下来,您可以应用 .aspectRatio 来适应尺寸或仅填充框架。

Example for simple usage of resizable:可调整大小的简单用法示例:

Image("somename")
.resizable()
.frame(width: 50px, height: 50px) 
Image(room.thumbnailImage)
    .resizable()
    .frame(width: 32.0, height: 32.0,alignment: .center)

In SwiftUI .resizable() attribute helps to resize an image.在 SwiftUI中, .resizable()属性有助于调整图像大小。 After that we can give some custom size.之后我们可以提供一些自定义尺寸。

Image(room.thumbnailImage) .frame(width: 32.0, height: 32.0)图像(room.thumbnailImage).frame(宽度:32.0,高度:32.0)

Add resizable and frame添加可调整大小和框架

.resizable() .frame( maxWidth: 600, maxHeight: 300,) .resizable() .frame( maxWidth: 600, maxHeight: 300,)

Use the font modifier with a dynamic type on an Image view:在 Image 视图上使用具有动态类型的字体修饰符:

Image(systemName: "nose")
        .font(.largeTitle)

204 204

If we have a large image in Assets.xcassets.如果我们在 Assets.xcassets 中有一个大图像。 then for resize this image with SwiftUI to make it small firstly we must use the resizable() and then use frame() .然后使用 SwiftUI 调整此图像的大小以使其变小,首先我们必须使用resizable()然后使用frame()

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

You have to make the image resizable then you can apply a frame for the image size you want.您必须调整图像大小,然后才能应用所需图像大小的框架。

Image("YOUR IMAGE NAME")
    .resizable()
    .frame(width: 32.0, height: 32.0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM