【问题标题】:Add a circular image view with corner radius for an image in swiftUI在 swiftUI 中为图像添加圆角半径的圆形图像视图
【发布时间】:2021-12-14 18:18:55
【问题描述】:

如何添加类似于下面附件的圆形视图。在附件中,检查是图像图标,我想以圆形添加绿色背景颜色。我在 Swift 中有一个解决方案,但在 swiftUI 中无法实现。

与我的问题相关的帖子:Add a border with cornerRadius to an Image in SwiftUI Xcode beta 5。但是,这并不能解决我的问题。

此实现的 Swift 代码:

var imageView = UIImageView()
override init(theme: Theme) {
    super.init(theme: theme)
    imageView.clipsToBounds = true
    setLayout()
  }

override func layoutSubviews() {
    super.layoutSubviews()
    let cornerRadius = frame.height / 2
    imageView.setCornerRadius(cornerRadius)
    setCornerRadius(cornerRadius)
  }

【问题讨论】:

    标签: image swiftui shapes cornerradius


    【解决方案1】:

    您可以像...一样创建此图像

    Image(systemName: "checkmark")
      .resizable()
      .frame(width: 20, height: 20)
      .foregroundColor(.white)
      .padding(20)
      .background(Color.green)
      .clipShape(Circle())
    

    或者……

    Image(systemName: "checkmark.circle.fill")
      .resizable
      .frame(width: 40, height: 40) // put your sizes here
      .foregroundColor(.green)
    

    【讨论】:

    • 图像没有名为 backgroundColor 的修饰符,对于您的第二个解决方案,foregroundColor 指的是前景元素的着色。它与背景颜色无关。你的解决方案都不起作用。
    • @Tejasree 我做了一些更改。我已经在手机的浏览器中编写了所有内容。但至于“你的解决方案都不起作用”。代码有 80% 在那里,并进行了一些大多数初学者可以自己找到的调整。第二个是在前景之后添加单词Color
    【解决方案2】:

    这不是最简单的办法。将此结构用作单独的视图。它将在圆圈上返回适当大小的图像。

    struct ImageOnCircle: View {
        
        let icon: String
        let radius: CGFloat
        let circleColor: Color
        let imageColor: Color // Remove this for an image in your assets folder.
        var squareSide: CGFloat {
            2.0.squareRoot() * radius
        }
        
        var body: some View {
            ZStack {
                Circle()
                    .fill(circleColor)
                    .frame(width: radius * 2, height: radius * 2)
                
                // Use this implementation for an SF Symbol
                Image(systemName: icon)
                    .resizable()
                    .aspectRatio(1.0, contentMode: .fit)
                    .frame(width: squareSide, height: squareSide)
                    .foregroundColor(imageColor)
                
                // Use this implementation for an image in your assets folder.
    //            Image(icon)
    //                .resizable()
    //                .aspectRatio(1.0, contentMode: .fit)
    //                .frame(width: squareSide, height: squareSide)
            }
        }
    }
    

    【讨论】:

    • 感谢您的解决方案。这非常有效。
    猜你喜欢
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多