Draw partially transparent UIView while using the backgroundColor
I'm creating a custom UIControl that renders it's view via drawRect:
. I want to use the existing backgro开发者_JAVA百科undColor property to permit customization via Interface Builder. However, if the backgroundColor is set, by the time drawRect: is called, the entire rectangle has already been filled in. I have opaque = NO and clearsContextBeforeDrawing = YES. If I set the backgroundColor to clearColor then I can render only the parts that I want.
How do I prevent the UIView from filling in the entire rectangle with the backgroundColor automatically?
I should mention that the custom control is placed in Interface Builder so the initWithCoder: method is being used to instantiate the object.
This should certainly possible as if you inherit from UIButton - which uses the backgroundColor - the rectangle has not been filled in.
You need to overide:
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx;
This is where the background color is applied. If you want the view to handle the background color, call the super's drawLayer method.
Since this is a custom control, could you add a variable UIColor *myColor
, and, in the init method, after it has been read from the nib, set myColor = self.backgroundColor
, and self.backgroundColor = [UIColor clearColor]
? Then obviously use myColor
in your drawRect.
I haven't tried this, and it seems a bit ugly, but maybe it works?
精彩评论