我想将我的navigationBar更改为以虚线为边框,如下所示:
我在此主题中找到了一个很好的答案,有关如何更改NavigationBar边框的颜色:Change navigation bar bottom border color Swift特别是:https://stackoverflow.com/a/46224261/436014
通过UIColor扩展名:
extension UIColor {
/// Converts this `UIColor` instance to a 1x1 `UIImage` instance and returns it.
///
/// - Returns: `self` as a 1x1 `UIImage`.
func as1ptImage() -> UIImage {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
setFill()
UIGraphicsGetCurrentContext()?.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
UIGraphicsEndImageContext()
return image
}
}
我想知道是否有任何方法可以改编虚线。我本以为可以通过以多种颜色填充填充来完成此操作,但由于它是单个UIcolor的扩展,因此感到困惑
navigationController.navigationBar.shadowImage = UIColor.black.as1ptImage()
因此,类似以下内容显然不起作用:
UIGraphicsBeginImageContext(CGSize(width: 1, height: 4))
UIGraphicsGetCurrentContext()?.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
UIGraphicsGetCurrentContext()?.fill(CGRect(x: 1, y: 0, width: 3, height: 1))
我想知道是否有人知道如何解决这个问题
答案 0 :(得分:0)
好的,我设法借助CALayer的API文档找到了解决方案:https://developer.apple.com/documentation/quartzcore/cashapelayer/1521921-linedashpattern
这个关于将CALayer转换为UIImage的线程:UIImage from CALayer in iOS
整个过程是:
CALayer
CALayer
赋予一个框架UIImage
navigationBar.shadowImage
有趣的是,它可以适当地平铺,因此CALayer / UIImage只需与您生成的虚线一样宽。
extension UIImage {
class func imageWithLayer(layer: CALayer) -> UIImage {
UIGraphicsBeginImageContextWithOptions(layer.bounds.size, layer.isOpaque, 0.0)
layer.render(in: UIGraphicsGetCurrentContext()!)
guard let img = UIGraphicsGetImageFromCurrentImageContext() else { return UIImage() }
UIGraphicsEndImageContext()
return img
}
}
let layer = CALayer()
layer.frame = CGRect(x: 0, y: 0, width: 6, height: 1)
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.lineWidth = 1
shapeLayer.lineDashPattern = [4,2]
let path = CGMutablePath()
path.addLines(between: [CGPoint(x:1, y: 0), CGPoint(x: 6, y:0)])
shapeLayer.path = path
layer.addSublayer(shapeLayer)
navigationController.navigationBar.shadowImage = UIImage.imageWithLayer(layer: layer)