如何在UIView中获取特定颜色的帧

时间:2013-10-11 09:18:46

标签: objective-c uiimage

我必须在frame中找到UIView的颜色,如下图所示:

enter image description here

在此图片中,我想找到frame个三角形,并希望为其添加UIControl

我可以实现吗?

1 个答案:

答案 0 :(得分:0)

创建一个具有两个属性的类:shape,color和image以及具有新属性UIImageView的子类imageObject。 (我只是认为YBImageObject是一个可怕的类名,所以如果你打算使用这个代码,请改变它)

viewDidLoad

NSArray *images = @[@{@"name": @"darkgreen-circle1", @"shape" : @"Circle",   @"color" : @"#8dc1b1"},
                    @{@"name": @"darkgreen-circle2", @"shape" : @"Circle",   @"color" : @"#8dc1b1"},
                    @{@"name": @"darkgreen-circle3", @"shape" : @"Circle",   @"color" : @"#8dc1b1"},
                    @{@"name": @"lightblue-square1", @"shape" : @"Square",   @"color" : @"#00c1f5"},
                    @{@"name": @"lightblue-square2", @"shape" : @"Square",   @"color" : @"#00c1f5"},
                    @{@"name": @"red-circle1",       @"shape" : @"Circle",   @"color" : @"#ff799a"},
                    @{@"name": @"yellow-triangle1",  @"shape" : @"Triangle", @"color" : @"#e3ff86"},
                    @{@"name": @"yellow-triangle2",  @"shape" : @"Triangle", @"color" : @"#e3ff86"}];


int i = 0;
for (NSDictionary *dictImage in images){
    YBImageObject *imageObject = [[YBImageObject alloc] init];
    [imageObject setImage:[UIImage imageNamed:[dictImage objectForKey:@"name"]]];
    [imageObject setShape:[dictImage objectForKey:@"shape"]];
    [imageObject setColor:[dictImage objectForKey:@"color"]];

    // imageView.frame.origin.x = total width of previous images * a little margin
    YBImageView *imageView = [[YBImageView alloc] initWithFrame:CGRectMake(i * 1.2, 100, imageObject.image.size.width, imageObject.image.size.height)];
    [imageView setBackgroundColor:[UIColor blackColor]];
    [imageView setImageObject:imageObject];
    [self.view addSubview:imageView];

    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGestures:)];
    [imageView addGestureRecognizer:tapGestureRecognizer];
    [imageView setUserInteractionEnabled:YES];

    i += imageObject.image.size.width;
}

handleTapGestures:

- (void) handleTapGestures:(UITapGestureRecognizer *)gestureRecognizer
{
    YBImageView *imageView = (YBImageView *)gestureRecognizer.view;

    NSLog(@"Shape: %@", imageView.imageObject.shape);
    NSLog(@"Color: %@", imageView.imageObject.color);
}

Source code