我在Assets.xcassets中有一个大图像。如何用SwiftUI调整这张图片的大小使它变小?
我试着设置框架,但它不起作用:
Image(room.thumbnailImage)
.frame(width: 32.0, height: 32.0)
我在Assets.xcassets中有一个大图像。如何用SwiftUI调整这张图片的大小使它变小?
我试着设置框架,但它不起作用:
Image(room.thumbnailImage)
.frame(width: 32.0, height: 32.0)
当前回答
在图像名称后使用. resized()方法。 确保在进行任何修改之前需要声明. resized()的用法。
是这样的:
Image("An Image file name")
.resizable()
//add other modifications here
其他回答
这个怎么样:
struct ResizedImage: View {
var body: some View {
Image("myImage")
.resizable()
.scaledToFit()
.frame(width: 200, height: 200)
}
}
图像视图为200x200,但图像保持原始宽高比(在该帧内重新缩放)。
因为我们不应该硬编码/修复图像大小。这里提供了一种更好的方法,可以根据不同设备上的屏幕分辨率进行调整。
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)
struct AvatarImage: View {
var body: some View {
Image("myImage")
.resizable()
.scaledToFill() // <=== Saves aspect ratio
.frame(width: 60.0, height:60)
.clipShape(Circle())
}
}
您可以使用resized()属性,但请记住,您不能在普通修饰符中使用resized,因此您必须使用Image扩展来实现它。
extension Image {
func customModifier() -> some View {
self
.resizable()
.aspectRatio(contentMode: .fit)
}
如果你想在swiftUI中调整图像大小,只需使用以下代码:
import SwiftUI
struct ImageViewer : View{
var body : some View {
Image("Ssss")
.resizable()
.frame(width:50,height:50)
}
}
但这里有个问题。 如果你在一个按钮中添加这个图像,图像将不会显示,只有一个蓝色块会在那里。 要解决这个问题,只需这样做:
import SwiftUI
struct ImageViewer : View{
var body : some View {
Button(action:{}){
Image("Ssss")
.renderingMode(.original)
.resizable()
.frame(width:50,height:50)
}
}
}