【问题标题】:SwiftUI Image clipsToBoundsSwiftUI Image clipsToBounds
【发布时间】:2019-11-11 11:56:47
【问题描述】:

尝试使用 SwiftUI(Xcode 11.0 beta 2),我尝试用图像填充视图:

Image("large")
    .resizable()
    .aspectRatio(contentMode: .fill)
    .frame(width: 80, height: 80, alignment: .center)
    .border(Color.black)

这样渲染:

我想应用类似于UIView.clipsToBounds 的东西,这样图像就会被剪裁,框外的部分不可见。

【问题讨论】:

    标签: ios swift swiftui


    【解决方案1】:

    你可以使用.clipped()修饰符,产生类似于UIView.clipsToBounds的效果:

    Image("large")
        .resizable()
        .aspectRatio(contentMode: .fill)
        .frame(width: 80, height: 80, alignment: .center)
        .border(Color.black)
        .clipped() // Equal to clipsToBounds = true
    

    【讨论】:

    • 请注意,剪辑必须跟随帧而不是在它之前,否则它将不起作用!
    • 重要提示:这在视觉上对我来说非常有用。我发现了一个问题,如果图像的剪切区域与按钮重叠,则该按钮将不起作用。即使它看起来很完美,按钮也不会收到应有的触摸。为了解决这个问题,在将图像发送到 SwiftUI Image 的 init(uiImage:) 之前,我必须手动将图像(使用 UIKit)剪辑到特定的 CGSize。我希望这对我的情况有所帮助!如果有人有更好的方法来处理这个问题,请告诉我。
    • @SeanRobinson159 我也遇到了同样的问题。我将框架对齐设置为 .top,因为我的按钮位于顶部,因此图像与底部的东西重叠,无需担心。但仍然非常不理想......:/
    • 您可以使用 ZStack 确保按钮位于顶部。
    【解决方案2】:
    Image("large")
       .resizable()
       .clipShape(Circle())
       .frame(width: 200.0, height: 200.0)
       .overlay(Circle().stroke(Color.white,lineWidth:4).shadow(radius: 10))
    

    【讨论】:

    • 不是我想要的,但clipShape 绝对很酷!
    【解决方案3】:
    Use GeometryReader can fix the issue where if the clipped region of the image overlaps a button, that button will NOT work
    
    like this:
    GeometryReader { geo in
       Image("large")
        .resizable()
        .aspectRatio(contentMode: .fill)
        .frame(width: 80, height: 80, alignment: .center)
        .border(Color.black)
     }.frame(width: 150, height: hh)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-13
      • 1970-01-01
      • 2015-03-06
      • 2014-07-08
      • 2017-01-20
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      相关资源
      最近更新 更多