如何从WKWebView获取点的RGBA像素颜色?
我有一个UIWebView的工作解决方案,但我想使用WKWebView。当我点击屏幕上的某个点时,我能够从UIWebView中检索RGBA中的颜色值,例如(0,0,0,0),当它是透明的时候(0.76,0.23,0.34,1)它不透明。 WKWebView总是返回(0,0,0,0)。
更多详情
我正在开发一个iOS应用程序,其中WebView是最顶级的ui元素。
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,它绘制实际的网页。
答案 0 :(得分:5)
#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
此代码修复了我的问题。