3

I am modifying an IOS app to allow an additional background layer. All the existing overlays are UIImageViews, which handle transparency just fine.

The existing background is the main UIView. I want to change the black background to transparent, to put another view behind. It doesn't work. The simplest code which doesn't work as I would hope is as follows:

# import "TestUIView.h"
@implementation TestUIView

- (void)drawRect:(CGRect)rect {

    self.opaque = NO;
    [self setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0]];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 0,0,0,0);
    CGContextFillRect(context, rect);
// and here goes my code where I draw to the transparent background
}
@end

When this is executed, it produces a black rectangle. I have set its background to transparent and filled its foreground with transparent. What do I have to do to get a UIView where I can draw against a transparent background?

(And I know I can change the alpha of the view as a whole, that's not the issue. I want opaque drawing on a truly transparent background).

UPDATE: Its not in the setbackgroundcolor, I appreciate it isn't necessary and so shouldn't be there, but the same thing happens if it is commented out. I can't draw against a transparent background; the code above shows I can't even make a transparent rectangle to draw onto.

Thanks

Peter Webb
  • 671
  • 4
  • 14

1 Answers1

4

By default the value of opaque is NO. Also if you set the alpha to 0, then the view will be completely invisible to the user.If you want to have transparency, then you need to have an alpha value greater than 0 and less than 1.

Also the backgroundColor property is used to set the view’s color rather than drawing that color yourself.

If you need to change the background color in drawRect, you will have to draw it yourself:

self.backgroundColor=yourColorWithSomeAlphaValue;//
[self.backgroundColor setFill];
CGContextFillRect(UIGraphicsGetCurrentContext(), rect);

More explanation is provided in here:

Community
  • 1
  • 1
Teja Nandamuri
  • 11,045
  • 6
  • 57
  • 109