2015-06-24 77 views
7

如何從WKWebView獲取點的RGBA像素顏色?iOS 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它繪製實際的網頁來。

回答

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 

此代碼解決了我的問題。

+0

通過將舊代碼中的[layer renderInContext:context];''更改爲'UIGraphicsPushContext(context); [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES]; UIGraphicsPopContext();'奇妙地工作..有時我不知道你們如何弄清楚這樣的事情。謝謝! – Bruce