【问题标题】:Swift: Get little strips, when add a border to UIImageViewSwift:在向 UIImageView 添加边框时获取小条
【发布时间】:2018-08-31 16:04:26
【问题描述】:

当我向 UIImageView 添加边框时,我在下图中看到黑色小条。我在真正的 iPhone 上试用我的应用程序,我也可以看到小条。我怎样才能删除这个或者这个问题在哪里?

有人有想法吗?

这是我的 UIImageView 代码:

//Setup ProfileImageView
    profileImageView.layer.cornerRadius = profileImageView.frame.size.width / 2
    profileImageView.clipsToBounds = true
    profileImageView.layer.borderColor = UIColor.white.cgColor
    profileImageView.layer.borderWidth = 4.0
    profileImageView.layer.shadowOpacity = 0.12
    profileImageView.layer.shadowOffset = CGSize(width: 0, height: 2)
    profileImageView.layer.shadowRadius = 2
    profileImageView.layer.shadowColor = UIColor.black.cgColor

还有我的故事板设置:

我使用的是 Xcode 10 beta 6...这会是个问题吗?

【问题讨论】:

  • 你是指截图边缘的黑色边框吗?
  • 不,我的意思是屏幕截图中圆形图像周围的黑色小边框

标签: ios swift


【解决方案1】:

当您设置cornerRadius 时,看起来图像正在溢出图层的边界。看到这个帖子:iOS: Rounded rectangle with border bleeds color

@FelixLam 在上述帖子中建议的CAShapeLayer 解决方案可能是这样的:

let lineWidth: CGFloat = 4.0 // the width of the white border that you want to set
let imageWidth = self.profileImageView.bounds.width
let imageHeight = self.profileImageView.bounds.height

// make sure width and height are same before drawing a circle
if (imageWidth == imageHeight) {
    let side = imageWidth - lineWidth
    let circularPath = UIBezierPath.init(ovalIn: CGRect(lineWidth / 2, lineWidth / 2, side, side))

    // add a new layer for the white border
    let borderLayer = CAShapeLayer()
    borderLayer.path = circularPath.CGPath
    borderLayer.lineWidth = lineWidth
    borderLayer.strokeColor = UIColor.white.cgColor
    borderLayer.fillColor = UIColor.clear.cgColor
    self.profileImageView.layer.insertSublayer(borderLayer, at: 0)

    // set the circle mask to your profile image view
    let circularMask = CAShapeLayer()
    circularMask.path = circularPath.CGPath
    self.profileImageView.layer.mask = circularMask
}

【讨论】:

  • 感谢您的回答。当我将此代码添加到我的项目时,我在这一行中收到以下错误:“let side = imageWidth - lineWidth”:二元运算符'-'不能应用于'CGFloat'和'Double'类型的操作数我该如何解决编译器问题?
  • 可能是因为第一行。默认情况下,lineWidth 将被声明为 Double。通过更改为 let lineWidth: CGFloat = 4.0 来修复它。无论如何,我也会更新我的答案
猜你喜欢
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-01
  • 1970-01-01
相关资源
最近更新 更多