如何使用SwiftUI调整图片大小?"/>
关于iOS:如何使用SwiftUI调整图片大小?
How to resize Image with SwiftUI?
我在Assets.xcassets中拥有很大的形象。 如何使用SwiftUI调整图像大小以缩小图像?
我试图设置框架,但不起作用:
1 | Image(room.thumbnailImage) |
在Image上应用任何大小修改之前,应使用.resizable()。
1 | Image(room.thumbnailImage).resizable() |
相关讨论
- 以及如何调整图像的尺寸并保持宽高比?
- @MarkKang我没有尝试过,但是有一个名为aspectRatio(_:contentMode:)的方法
- 该方法要求您指定纵横比。我想保留图像的原始长宽比,但要通过帧高度限制它最适合,将图像内容居中并按帧裁剪。
- @MarkKang我不知道您是否可以动态地做到这一点。一种解决方案是对实际图像的纵横比进行硬编码。
- Image(" image01").resizable().aspectRatio(UIImage(name:" image01")!. size,contentMode:.fit)
- @MarkKang-我的版本是:Image(person.photo).resizable()。aspectRatio(contentMode:ContentMode.fit)
- 那样就好了。但我认为这里有一个适合的错误。 hackingwithswift/swiftui/
- 但是,Image("name").resizable().scaledToFit()没有错误。因此,您可以将图像包装在视图中,将视图的框架调整为所需的任何大小,然后scaledToFit()将使图像尽可能大,同时保持宽高比。
- Image("name").resizable().scaledToFit()不为我保留原始的宽高比
这个怎么样:
1 | struct ResizedImage: View { |
图像视图为200x200,但是图像保持原始宽高比(在该帧内缩放)
相关讨论
- 在我的情况下,此解决方案不保留原始的宽高比。
- @ pm89您原始和最终图像/视图的尺寸是多少?
- 原始宽高比为3/2,结果变为1/1,从而拉伸了图像。这似乎是一个SwiftUI错误。我最终在接受答案下的注释中使用了Mark Kang的建议方法,其中image是UIImage类型,因为image类型没有公开任何size属性。
- 对我来说,它的工作方式包括保持宽高比,谢谢?
扩展@rraphael的答案和评论:
从Xcode 11 beta 2开始,您可以将图像缩放到任意尺寸,同时通过将图像包装在另一个元素中来保持原始宽高比。
例如
1 | struct FittedImage: View |
结果
(由于某种原因,图像显示有点模糊。请确保实际输出清晰。)
相关讨论
- 您可能会在SO上看到模糊的图像,因为您使用的是高DPI监视器。我将其放在常规DPI显示器上,看起来很清晰
- 仅当原始图像的纵横比为1(图像为正方形)并且您正在使用.aspectRatio(1, ...时,这才保留原始的纵横比。并不是说到目前为止任何其他解决方案都对我有用...
在SwiftUI中使用.resizable()调整图像大小
1 | Image("example-image") |
Note : My image name is img_Logo and you can change image name define image properties this:
1 | VStack(alignment: .leading, spacing: 1) { |
相关讨论
- 我强烈建议您在编写代码时写一段简短的文字,并附上某种解释。请在此处查看行为准则:stackoverflow/conduct
由于我们不应该硬编码/固定图像大小。这是提供更好的范围以根据不同设备上的屏幕分辨率进行调整的更好方法。
1 | Image("ImageName Here") |
如果要在调整大小时使用宽高比,则可以使用以下代码:
1 | Image(landmark.imageName).resizable() |
另一种方法是使用scaleEffect修饰符:
1 | Image(room.thumbnailImage) |
1 | struct AvatarImage: View { |
如果要在swiftUI中调整图像大小,请使用以下代码:
1 | import SwiftUI |
但是这里有问题。
如果将此图像添加到按钮内,则不会显示该图像,仅会出现蓝色的块。
要解决此问题,只需执行以下操作:
1 | import SwiftUI |
好吧,在SwiftUI中似乎很容易/按照他们给出的演示进行操作:
1 | struct RoomDetail: View { |
希望能帮助到你。
理解代码的逻辑结构非常重要。像在SwiftUI中一样,图片默认情况下无法调整大小。因此,要调整任何图像的大小,必须在声明"图像"视图后立即应用.resizable()修饰符使其可调整大小。
1 | Image("An Image file name") |
您可以定义图像属性,如下所示:
1 | Image("\\(Image Name)") |
使用以下代码。
1 | Image("image") |
更多推荐
关于iOS:如何使用SwiftUI调整图片大小?
发布评论