有没有办法可以根据屏幕上的位置检索对象/对象(例如UILabel
,UIButton
,UIView
等)?例如,如何确定哪个元素位于(100,100)点之上?
我问的原因是因为我想访问位于特定点的最顶层对象的backgroundColor
属性?
答案 0 :(得分:0)
可以在场景中获得一个点的颜色,但不知道是否可以识别那里的物体。 为了获取屏幕中某点的颜色,这是一个解决方案。考虑像
这样的观点CGPoint aPoint = CGPointMake(100, 100);
您可以在ios Core Graphics框架的帮助下获得此处的颜色,如
unsigned char pixel[4] = {0};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, kCGBitmapAlphaInfoMask & kCGImageAlphaPremultipliedLast);
CGContextTranslateCTM(context, -aPoint.x, -aPoint.y);
[self.view.layer renderInContext:context];
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
UIColor *color = [UIColor colorWithRed:pixel[0]/255.0 green:pixel[1]/255.0 blue:pixel[2]/255.0 alpha:pixel[3]/255.0];
答案 1 :(得分:0)
UIView's
方法- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
完全符合您的要求。
UIView *hitView = [self.view hitTest:location withEvent:nil];
根据文件Returns the farthest descendant of the receiver in the view hierarchy (including itself) that contains a specified point.
但是This method ignores view objects that are hidden, that have disabled user interactions, or have an alpha level less than 0.01. This method does not take the view’s content into account when determining a hit. Thus, a view can still be returned even if the specified point is in a transparent portion of that view’s content.
如果你想获得被排除的视图,你必须为此编写自己的递归方法。类似的东西(仍然不考虑视图的内容):
- (UIView *)getHitView:(UIView*)parent location:(CGPoint)location{
for(UIView *v in parent.subviews.reverseObjectEnumerator){
if(CGRectContainsPoint(v.frame, location)){
return [self getHitView:v location:[v convertPoint:location fromView:parent]];
}
}
return parent;
}