简体   繁体   中英

Changing color of small portion of UIView?

I have a UIView whose color is black and opacity is 0.9 or something like that. What I want to do is to fill the UIView with black portion, but a specified rectangular area should not get black. ie that particular rectangular area remains with clear color...

Any kind of help will be appreciated.

regards,

Imran

You can subclass UIView and override - (void)drawRect:(CGRect)rect

And do something of the following (untested, but used something similar myself);

- (void)drawRect:(CGRect)rect {

// fill the whole UIView with a color
[[UIColor colorWithRed:1 green:1 blue:1 0.9] setFill];
UIRectFill( rect );

// draw a rect
CGRect rectIntersection = CGRectIntersection(theRectIWantToDrawIn, rect);

[[UIColor clearColor] setFill];
UIRectFill( rectIntersection );
}

The code above draws a black view with a simulated clearColor hole in it at a certain position. You could, of course, alter this behavior to your liking.

This is quite fast.

UPDATE: Do note that I set the UIView on which I want to draw the rect to UIClear color (I added it to a xib and set those properties there) and unchecked 'Opaque'. That should make the hole see-through.

UPDATE 2: My answer was based on this answer (credit where credit is due): iPhone - Draw transparent rectangle on UIView to reveal view beneath

Add another view (subview) to that area. And set its to your desired color. Thats the easy solution with your current requirements. Or you can use some quartz core functions.

You can create a small UIView in the main view by custom and set background clear color

UIView *View1 = [[UIView alloc] initWithFrame:CGRectMake(128.0f, 50.0f, 34.0f, 34.0f)];
[View1 setBackgroundColor:[UIColor clearColor]];        
[self.view addSubview:View1];
[View1 release];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM