如何从 WKWebView 获取点的 RGBA 像素颜色?
我有一个适用于 UIWebView 的可行解决方案,但我想改用 WKWebView。当我点击屏幕上的某个点时,我能够从 UIWebView 中检索 RGBA 中的颜色值,例如 (0,0,0,0) 当它是透明的或类似 (0.76,0.23,0.34,1) 时它不透明。 WKWebView 始终返回 (0,0,0,0)。
更多详情
我正在开发一个将 WebView 作为最顶级 ui 元素的 iOS 应用。
WebView 具有透明区域,因此您可以看到底层的 UIView。
WebView 应忽略对透明区域的触摸,底层 UIView 应检索该事件。
因此我重写了 hitTest 函数:
#import "OverlayView.h"
#import <QuartzCore/QuartzCore.h>
@implementation OverlayView
-(UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event {
UIView* subview = [super hitTest:point withEvent:event]; // this will always be a webview
if ([self isTransparent:point fromView:subview.layer]) // if point is transparent then let superview deal with it
{
return [self superview];
}
return subview; // return webview
}
- (BOOL) isTransparent:(CGPoint)point fromView:(CALayer*)layer
{
unsigned char pixel[4] = {0};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
CGContextTranslateCTM(context, -point.x, -point.y);
[layer renderInContext:context];
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return (pixel[0]/255.0 == 0) &&(pixel[1]/255.0 == 0) &&(pixel[2]/255.0 == 0) &&(pixel[3]/255.0 == 0) ;
}
@end
我的假设是 WKWebView 有一个不同的 CALayer 或一个隐藏的 UIView,它在其中绘制实际的网页。
最佳答案
#import "OverlayView.h"
#import <QuartzCore/QuartzCore.h>
@implementation OverlayView
-(UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event {
UIView* subview = [super hitTest:point withEvent:event]; // this should always be a webview
if ([self isTransparent:[self convertPoint:point toView:subview] fromView:subview.layer]) // if point is transparent then let superview deal with it
{
return [self superview];
}
return subview; // return webview
}
- (BOOL) isTransparent:(CGPoint)point fromView:(CALayer*)layer
{
unsigned char pixel[4] = {0};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
CGContextTranslateCTM(context, -point.x, -point.y );
UIGraphicsPushContext(context);
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
UIGraphicsPopContext();
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return (pixel[0]/255.0 == 0) &&(pixel[1]/255.0 == 0) &&(pixel[2]/255.0 == 0) &&(pixel[3]/255.0 == 0) ;
}
@end
这段代码解决了我的问题。
关于iOS WKWebView 从点获取 RGBA 像素颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31038306/