iOS WKWebView从点获取RGBA像素颜色

iOS WKWebView get RGBA pixel color from point

如何从 WKWebView 获取点的 RGBA 像素颜色?

我有一个适用于 UIWebView 的解决方案,但我想改用 WKWebView。当我点击屏幕上的一个点时,我能够从 UIWebView 中检索 RGBA 中的颜色值,例如 (0,0,0,0) 当它是透明的或类似 (0.76,0.23,0.34,1) 时它不透明。 WKWebView 总是 return (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,它在其中绘制实际的网页。

#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

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