2

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. i.e. that particular rectangular area remains with clear color...

Any kind of help will be appreciated.

regards,

Imran

Viktor Apoyan
  • 10,655
  • 22
  • 85
  • 147
Imran
  • 33
  • 6

3 Answers3

5

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

Community
  • 1
  • 1
Jake
  • 3,973
  • 24
  • 36
  • Excellent ! This is somewhat what i wanted :) Never knew about an intersection rect ... but I have a problem with it ..the above code does give me a hole in main view ... but the the part where i am supposed to have clear color (i.e. the inner rectangle); if i use 'clearColor', it gives returns black color inside. Not quite what i had anticipated, because I must have clear color to let the user have a peek at the background view ..any thoughts ? – Imran May 12 '11 at 11:16
  • I think I forgot to mention that you have to set some properties on the view. Updated my earlier answer. – Jake May 12 '11 at 11:32
0

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.

karim
  • 15,408
  • 7
  • 58
  • 96
0

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];
Hemang
  • 26,840
  • 19
  • 119
  • 186
Deepesh
  • 633
  • 4
  • 11