gpt4 book ai didi

ios - 如何为 UINavigationBar 设置不透明的 1px 高阴影图像?

转载 作者:技术小花猫 更新时间:2023-10-29 11:16:12 26 4
gpt4 key购买 nike

在我的应用程序委托(delegate)的 didFinishLaunchingWithOptions 函数中,我尝试自定义导航栏的外观。

[UINavigationBar appearance].translucent = NO;
[[UINavigationBar appearance]
setBackgroundImage:[UIImage
imageWithColor:[UIColor whiteColor]
size:CGSizeMake(1.0f, 1.0f)
]
forBarMetrics:UIBarMetricsDefault
];
[UINavigationBar appearance].shadowImage = [UIImage
imageWithColor:[UIColor redColor]
size:CGSizeMake(0.5f, 0.5f)
];

我希望有一个 1px 高的不透明红色阴影。相反,我得到了一个 2px 高的半透明红色阴影。如何让它完全按照我想要的样子出现?我已经对 UITabBar 进行了类似的外观设置。另一方面,它表现得很好。

enter image description here

创建动态图像的类别函数定义如下:

+ (UIImage*)imageWithColor:(UIColor *)color size:(CGSize)size
{
CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}

最佳答案

您需要创建一个视网膜感知的图形上下文:

let pixelScale = UIGraphicsBeginImageContextWithOptions(fillRect.size, false, UIScreen.main.scale)

之后,您的阴影图像将变为 1 个物理像素高。

完整代码如下:

extension UIImage {

static func imageWithColor(color: UIColor) -> UIImage {
let pixelScale = UIScreen.main.scale
let pixelSize = 1 / pixelScale
let fillSize = CGSize(width: pixelSize, height: pixelSize)
let fillRect = CGRect(origin: CGPoint.zero, size: fillSize)
UIGraphicsBeginImageContextWithOptions(fillRect.size, false, pixelScale)
let graphicsContext = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(graphicsContext, color.CGColor)
CGContextFillRect(graphicsContext, fillRect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}

}

在 GitHub 上:

https://github.com/salutis/swift-image-with-color

关于ios - 如何为 UINavigationBar 设置不透明的 1px 高阴影图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27258003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com