UINavigationBar背景图片重复显示问题求助
我之前也碰到过一模一样的情况!这种图片重复+出现分割线的问题,大多是图片的拉伸配置不对,或者导航栏默认的阴影层干扰导致的,给你几个实用的解决办法:
1. 给背景图设置正确的拉伸模式
默认情况下,UIImage会按比例拉伸填充整个导航栏,如果你的图片没有设置合适的capInsets,就容易出现重复拼接的情况。你可以用resizableImage方法来指定图片的可拉伸区域,让非拉伸区域保持原样:
if let originalImage = UIImage(named: "Image_Name") { // 根据你的图片实际情况设置capInsets:如果图片上下/左右有不需要拉伸的部分,就对应设置数值 let resizableImage = originalImage.resizableImage( withCapInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0), resizingMode: .stretch ) navigationController?.navigationBar.setBackgroundImage(resizableImage, for: .default) }
举个例子:如果你的背景图底部有一条1px的装饰线,就把bottom设为1,这样拉伸时这条线不会被重复复制。
2. 隐藏导航栏默认的阴影线
你截图里的那条“分割线”,大概率是导航栏默认的shadowImage,不是图片重复导致的!可以直接把它设为空图片来隐藏:
navigationController?.navigationBar.shadowImage = UIImage()
记得同时要把导航栏的isTranslucent设为false(如果需要完全不透明的背景),不然可能会有半透明的残留:
navigationController?.navigationBar.isTranslucent = false
3. 确保图片尺寸适配导航栏高度
不同设备的导航栏高度不一样(比如带刘海的iPhone导航栏更高),如果你的图片尺寸固定,缩放后就容易出现重复。建议:
- 用PDF格式的矢量图,这样可以自适应任意尺寸而不失真
- 或者在代码里根据导航栏的实际高度动态调整图片大小:
if let originalImage = UIImage(named: "Image_Name"), let navBar = navigationController?.navigationBar { let targetSize = CGSize(width: navBar.bounds.width, height: navBar.bounds.height) UIGraphicsBeginImageContextWithOptions(targetSize, false, UIScreen.main.scale) originalImage.draw(in: CGRect(origin: .zero, size: targetSize)) let resizedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() navigationController?.navigationBar.setBackgroundImage(resizedImage, for: .default) }
先试试前两个办法,应该就能解决你看到的重复和分割线问题啦!
内容的提问来源于stack exchange,提问作者Anshul Bhatheja
相关产品推荐
相关产品推荐

