在 Swift 中,我可以创建UIImageView任何尺寸,然后只需设置contentMode = .center
原始尺寸的图像将出现在 ImageView 的中心。
如何使用 SwiftUI 实现这一点?
这就是我想要实现的目标:
所以我想创建带有圆角和背景颜色的图像(36 x 36)。并将图像设置在中心。怎么做 ?
这是我尝试过的:
Image("pool_icn")
.resizable()
.background(Color.blue)
.cornerRadius(16)
.frame(width: 36, height: 36, alignment: .center)
}
Run Code Online (Sandbox Code Playgroud)
结果是:
因此图像也调整了大小,而我希望它保持原始大小。
Image 可以吗?或者我应该将图像包装在容器中?
我把它放在一起,复制了你想要的东西。我使用了stethoscope系统映像,但我确信您应该能够将其更新为您需要的具体内容......
struct ContentView: View {
let imageSize: Double = 24
let circleSize: Double = 36
var body: some View {
Image(systemName: "stethoscope")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: imageSize, height: imageSize)
.frame(width: circleSize, height: circleSize)
.background(Color.blue)
.clipShape(Circle())
}
}
Run Code Online (Sandbox Code Playgroud)
我添加了imageSize和circleSize只是为了玩一下它们。
输出看起来大约是正确的......
您只需要该Image部分。我刚刚添加了视图以表明它没有使用其他任何东西。
Image我在其上创建了一个扩展iconify...
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "stethoscope")
.iconified(imageSize: 30, surroundSize: 50, color: .red)
Image(systemName: "car")
.iconified(imageSize: 100, surroundSize: 150, color: .green)
Image(systemName: "lungs")
.iconified(imageSize: 20, surroundSize: 36, color: .blue)
Image(systemName: "keyboard.onehanded.right")
.iconified(imageSize: 40, surroundSize: 60, color: .orange)
}
}
}
extension Image {
func iconified(imageSize: Double, surroundSize: Double, color: Color) -> some View {
self
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: imageSize, height: imageSize)
.frame(width: surroundSize, height: surroundSize)
.background(color)
.clipShape(Circle())
}
}
Run Code Online (Sandbox Code Playgroud)
这很好用...
如果您希望图像的大小保持在应有的大小,那么您可以这样做......
extension Image {
func iconified(surroundSize: Double, color: Color) -> some View {
self
.frame(width: surroundSize, height: surroundSize)
.background(color)
.clipShape(Circle())
}
}
Run Code Online (Sandbox Code Playgroud)
这将始终使图像保持在中心,其尺寸直接来自文件。这看起来像...
| 归档时间: |
|
| 查看次数: |
1683 次 |
| 最近记录: |