Ios 自定义绘制矩形由背景色覆盖
我创建了一个自定义UIView,在背景的顶部绘制一个“孔”Ios 自定义绘制矩形由背景色覆盖,ios,uiview,drawrect,Ios,Uiview,Drawrect,我创建了一个自定义UIView,在背景的顶部绘制一个“孔” @implementation MaskWithHole - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.hole = CGRectZero; self.holeColor = [UIColor clearColor]; } return s
@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);
当我把洞的颜色从透明变为绿色时,我能看到绿色——因此,在所有事物的背景下,它都画出了背景。 < P>在固体背景的中间有一个透明的孔的简单方法是使用一个具有中等透明度的PNG图像。还有外面的纯色。这似乎有效
@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
所以你想要一个背景颜色和透明部分的视图,让你在屏幕上看到它下面的视图?是的。我希望设置背景色-孔为不同的颜色-例如透明或其他颜色-可能重复尝试但不起作用的颜色…然后查看
CALayer*mask
。