在 swiftUI 中为图像添加带有角半径的圆形图像视图

Tej*_*ree 14 image shapes cornerradius swiftui

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

与我的问题相关的帖子:Add a border withcornerRadius 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)
  }
Run Code Online (Sandbox Code Playgroud)

检查图像

Fog*_*ter 23

你可以像这样创建这个图像...

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

或者另一种选择...

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


Yrb*_*Yrb 7

这不是最简单的事情。使用此结构作为单独的视图。它将返回圆圈上尺寸正确的图像。

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)