【发布时间】:2015-11-25 18:46:40
【问题描述】:
您好,我想在覆盖 UIView 的右下角创建一个四分之一透明的孔。
我可以使用下面的代码来解决它。但它看起来不正确,因为我在视野之外创建了一个矩形。
我尝试过的:
@implementation PartialTransparentView
- (id)initWithBottomRightCornerRadiusForView:(UIView *)view withRadius:(CGFloat)radius
{
[self commonInitWithRect:CGRectMake(view.frame.size.width - radius, view.frame.size.height - radius, radius*2, radius*2)];
self = [super initWithFrame:CGRectMake(0, 0, 5000, 5000)];//**it does not look right to me**
if (self) {
// Initialization code
self.opaque = NO;
}
return self;
}
-(void)commonInitWithRect:(CGRect)rect{
backgroundColor = [UIColor colorWithWhite:1 alpha:0.75];
rectToBeSurrounded = rect;
}
- (void)drawRect:(CGRect)rect {
[backgroundColor setFill];
UIRectFill(rect);
CGFloat x = rectToBeSurrounded.origin.x;
CGFloat y = rectToBeSurrounded.origin.y;
CGFloat width = rectToBeSurrounded.size.width;
CGFloat height = rectToBeSurrounded.size.height;
//create outer square
CGFloat outerX = (x - width/2);
CGFloat outerY = y - height/2;
CGFloat outerWidth = 2*width;
CGFloat outerHeight = outerWidth;
//create outer square
CGRect outerRect = CGRectMake(outerX, outerY, outerWidth, outerHeight);
CGRect holeRectIntersection = CGRectIntersection( outerRect, rect );
CGContextRef context = UIGraphicsGetCurrentContext();
if( CGRectIntersectsRect( holeRectIntersection, rect ) )
{
CGContextAddEllipseInRect(context, holeRectIntersection);
CGContextClip(context);
CGContextClearRect(context, holeRectIntersection);
CGContextSetFillColorWithColor( context, [UIColor clearColor].CGColor );
CGContextFillRect( context, holeRectIntersection);
}
}
现在我将上面的代码用作:
PartialTransparentView *transparentView = [[PartialTransparentView alloc] initWithBottomRightCornerRadiusForView:self.view withRadius:50];
[self.view addSubview:transparentView];
结果如预期:
我知道如果我必须实现相同的目标但在视图的左上角,我的解决方案将会中断。 我正在寻找的只是提供圆的中心 (x, y) 和半径并获得所需的结果。
谢谢 基于T先生
UIView *transparentView = [[UIView alloc] initWithFrame:self.view.frame];
[transparentView setBackgroundColor:[UIColor colorWithWhite:1 alpha:0.75]];
[self.view addSubview:transparentView];
circleView *acircleView = [[circleView alloc] initWithFrame:CGRectMake(50, 50, 60, 60)];
[acircleView setBackgroundColor:[UIColor grayColor]];
[transparentView addSubview:acircleView];
和circleView.m
- (void)drawRect:(CGRect)rect {
// Drawing code
//// Oval Drawing
UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(50, 50, 60, 60)];
[UIColor.grayColor setFill];
[ovalPath fill];
}
【问题讨论】:
-
你需要一种方法来传递参数来绘制 Rect 方法吗?你问的是这个吗?
-
基本上我的 drawRect 依赖于 rectToBeSurrounded 变量。至于创建一个圆圈,我必须创建一个正方形。我能够在 commonInitWithRect 中初始化/填充这个 var
-
你不要简单地用贝塞尔路径画一个圆圈,然后根据需要在叠加层上移动它吗?
-
5000、5000 的视图宽度高度看起来不错。我做错了什么,所以我必须接受 5000、5000。如果我不接受 5000,则不需要 5000 的结果
-
让我提供一种方法来完成您的任务
标签: ios objective-c uiview core-graphics