首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SwiftUI:镜像contentMode中心

SwiftUI:镜像contentMode中心
EN

Stack Overflow用户
提问于 2021-09-28 18:19:26
回答 1查看 146关注 0票数 1

在Swift中,我可以创建任何大小的UIImageView,然后只需设置contentMode = .center,图像中的原始大小将显示在ImageView的中心。

如何使用SwiftUI实现这一点?

这就是我想要实现的:

所以我想创建具有圆角和背景颜色的图像(36 X 36)。并将图像设置在中心。如何做到这一点?

这是我尝试过的:

代码语言:javascript
复制
Image("pool_icn")
                .resizable()
                .background(Color.blue)
                .cornerRadius(16)
                .frame(width: 36, height: 36, alignment: .center)
        }

结果是:

所以图像也调整了大小,而我希望它保持原始大小。

这可以用Image实现吗?或者我应该将图像包装在容器中?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-28 18:34:36

我把这些放在一起,有点复制了你想要的东西。我使用的是stethoscope系统镜像,但我相信您应该能够将其更新为您需要的特定内容……

代码语言:javascript
复制
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())
  }
}

我添加了imageSizecircleSize,只是为了稍微玩玩一下。

输出看起来是正确的……

您将只需要Image部件。我只是添加了视图,以显示它没有使用任何其他内容。

更多的游戏

我在Image上创建了一个扩展来iconify它...

代码语言:javascript
复制
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())
  }
}

这很有效..。

停止调整图像大小

如果你希望图像的大小保持在它应该是的大小,那么你可以这样做……

代码语言:javascript
复制
extension Image {
  func iconified(surroundSize: Double, color: Color) -> some View {
    self
      .frame(width: surroundSize, height: surroundSize)
      .background(color)
      .clipShape(Circle())
  }
}

这将始终保持图像在中心的大小,它直接从文件中。这看起来像..。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69366718

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档