我创建了一个自定义UIView来在背景上绘制一个“洞”
@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
但是自定义绘图始终是背景颜色 - 忽略drawRect代码
CGRect holeRect = self.hole;
CGRect holeRectIntersection = CGRectIntersection( holeRect, rect );
[self.holeColor setFill];
UIRectFill(holeRectIntersection);
当我将孔的颜色从透明变为绿色时,我可以看到绿色 - 所以这种方法很吸引人地在所有东西上绘制背景
答案 0 :(得分:0)
在纯色背景中间设置透明孔的简单方法是使用该尺寸的png图像,中间为透明,外部为纯色。
答案 1 :(得分:0)
这似乎有效
@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