【发布时间】:2020-02-04 00:31:26
【问题描述】:
我从 PNG 加载了带有 RGBA UIImage 的 MKOverlayRenderer。图片透明部分的 alpha 值为 0,半透明部分的 alpha 值为 160。
但是,当我在地图上渲染图像时,颜色有点褪色,整个图像看起来像是在雾后面。此问题是在更新到 iOS 13 后发生的,旧版本可以正常工作。
我通过[UIImage imageNamed:@"some_img"];加载图片
我扩展了MKOverlayRenderer,并覆盖了drawMapRect 方法:
- (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context {
UIImage * img = [UIImage imageNamed:@"some_img"];
MKMapRect theMapRect = self.overlay.boundingMapRect;
CGRect theRect = [self rectForMapRect:theMapRect];
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextTranslateCTM(context, 0.0, -theRect.size.height);
CGContextDrawImage(context, theRect, img.CGImage);
}
我尝试通过创建副本并使用以下公式手动处理 RGBA 像素,从图像中手动删除预乘 alpha(将 alpha 设置为 255 而不是 160):
CGImageRef sourceImage = img.CGImage;
CFDataRef theData;
theData = CGDataProviderCopyData(CGImageGetDataProvider(sourceImage));
UInt8 *pixelData = (UInt8 *) CFDataGetBytePtr(theData);
int dataLength = CFDataGetLength(theData);
for (int i = 0; i < dataLength; i += 4){
uint8_t aHalf = pixelData[i + 3] / 2;
pixelData[i + 0] = (pixelData[i + 0] * 255 + aHalf) / pixelData[i + 3];
pixelData[i + 1] = (pixelData[i + 1] * 255 + aHalf) / pixelData[i + 3];
pixelData[i + 2] = (pixelData[i + 2] * 255 + aHalf) / pixelData[i + 3];
pixelData[i + 3] = (pixelData[i + 3] == 0) ? 0 : 255;
}
CGContextRef context;
context = CGBitmapContextCreate(pixelData,
CGImageGetWidth(sourceImage),
CGImageGetHeight(sourceImage),
8,
CGImageGetBytesPerRow(sourceImage),
CGImageGetColorSpace(sourceImage),
kCGImageAlphaPremultipliedLast);
UIImage *newImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];
然后我在drawMapRect中设置CGContextSetAlpha(context, 0.6);。
这部分解决了问题,但在较旧的 iOS 版本上,图像的透明度不如 iOS 13,而且整个过程需要时间。
【问题讨论】:
标签: objective-c uiimage mkmapview alpha