Question

I created a custom UIView to draw a "hole" ontop of a background

@implementation MaskWithHole

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        self.hole = CGRectZero;
        self.holeColor = [UIColor clearColor];
    }
    return self;
}

-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    return nil;
}
-(void)setHole:(CGRect)hole
{
    _hole = hole;
    [self setNeedsDisplay];
}

-(void)setHoleColor:(UIColor *)holeColor
{
    _holeColor = holeColor;
    [self setNeedsDisplay];
}


- (void)drawRect:(CGRect)rect
{

    [self.backgroundColor setFill];
    UIRectFill(rect);

    // clear the background in the given rectangles

    CGRect holeRect = self.hole;
    CGRect holeRectIntersection = CGRectIntersection( holeRect, rect );
    [self.holeColor setFill];
    UIRectFill(holeRectIntersection);

}


@end

But the custom drawing is always the background color - disregarding the drawRect code

CGRect holeRect = self.hole;
    CGRect holeRectIntersection = CGRectIntersection( holeRect, rect );
    [self.holeColor setFill];
    UIRectFill(holeRectIntersection);

when I change the color of the hole from clear to green i can see the green- so apperantly the method is drawing teh background on everything

Was it helpful?

Solution 2

This seems to work

@interface MaskWithHole : UIView

// default cgrectzero
@property (nonatomic,assign) CGRect hole;

// default [uicolor clearcolor]
@property (nonatomic,strong) UIColor *holeColor;
@end


@interface MaskWithHole ()

@property (nonatomic,strong) UIColor *backGroundColorForMask;
@end
@implementation MaskWithHole

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        self.hole = CGRectZero;
        self.holeColor = [UIColor clearColor];
        self.backgroundColor = [UIColor clearColor];
        self.opaque = NO;
    }
    return self;
}

-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    return nil;
}
-(void)setHole:(CGRect)hole
{
    _hole = hole;
    [self setNeedsDisplay];
}

-(void)setHoleColor:(UIColor *)holeColor
{
    _holeColor = holeColor;
    [self setNeedsDisplay];
}

-(void)setBackgroundColor:(UIColor *)backgroundColor
{
    [super setBackgroundColor:[UIColor clearColor]];
    self.backGroundColorForMask = backgroundColor;
}
- (void)drawRect:(CGRect)rect
{
    [self.backGroundColorForMask setFill];
    UIRectFill(rect);

    CGRect holeRectIntersection = CGRectIntersection( self.hole, rect );
    [[UIColor clearColor] setFill];
    UIRectFill(holeRectIntersection);
}


@end

OTHER TIPS

The easy way to have a transparent hole in the middle of a solid background is using a png image of that size with transparency in the middle, and the solid color outside.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top