iOS中WKWebView获取指定点的RGBA像素颜色

8
我该如何从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,它将实际的网页绘制到其中。

1个回答

6
#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

这段代码解决了我的问题。


通过将旧代码中的 [layer renderInContext:context]; 更改为 UIGraphicsPushContext(context); [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES]; UIGraphicsPopContext();,一切都很好地解决了.. 有时候我真不知道你们是如何发现这样的事情的。谢谢! - Bruce

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接