ios - 在swift中将navigationBar底部边框更改为虚线
问题描述
我想将我的导航栏更改为以虚线作为边框,如下所示:
我在这个线程中找到了一个关于如何更改导航栏边框颜色的精彩答案:更改导航栏底部边框颜色 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))
我想知道是否有人知道如何解决这个问题
解决方案
好的,我设法通过 CALayer 的 API 文档找到了解决方案:https ://developer.apple.com/documentation/quartzcore/cashapelayer/1521921-linedashpattern
还有这个关于将 CALayer 转换为 UIImage 的 SO 线程:iOS 中来自 CALayer 的 UIImage
总体流程是:
- 创建一个
CALayer
- 给这个
CALayer
框架 - 画一条虚线
- 转换成
UIImage
- 使用这个 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)
推荐阅读
- asp.net-core - EF Core 3 x.where 扩展方法返回 IEnumerable 而不是 IQueryable
- javascript - 如何传递数字 id 而不是字符串 id?
- python - 在 Python 中定义函数后如何更改函数范围内的变量?
- reactjs - 使用 Firebase 身份验证检查反应路由器受保护的路由
- ruby - 以 sudo 运行创建的 gem
- visual-studio-code - 以编程方式检测浅色与深色主题
- linux - 如何检查linux实例中任何脚本的最后运行时间
- dokku - Dokku 上的时区信息 (zoneinfo) 已过期。如何更新?
- python - df_dates = df.loc[:,'Date'] 无法读取“日期”列(数据来自 yahoo Fin)
- java - Java 软件工程:组合与聚合