在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)
}结果是:

所以图像也调整了大小,而我希望它保持原始大小。
这可以用Image实现吗?或者我应该将图像包装在容器中?
发布于 2021-09-28 18:34:36
我把这些放在一起,有点复制了你想要的东西。我使用的是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())
}
}我添加了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())
}
}这很有效..。

停止调整图像大小
如果你希望图像的大小保持在它应该是的大小,那么你可以这样做……
extension Image {
func iconified(surroundSize: Double, color: Color) -> some View {
self
.frame(width: surroundSize, height: surroundSize)
.background(color)
.clipShape(Circle())
}
}这将始终保持图像在中心的大小,它直接从文件中。这看起来像..。

https://stackoverflow.com/questions/69366718
复制相似问题