0

我正在尝试在视图中间绘制一个透明的正方形(仅限边框),但我很难找出方法。我想我有两个问题,第一个是关于绘制一个带有黑色边框的透明正方形,第二个是将它放在视图的中间。

有什么好的教程可以学习吗?

更新

我尝试按照 Apple 教程进行操作,并且有一段代码可以在我的视图控制器中绘制一个矩形:

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2.0);
    CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
    CGRect rectangle = CGRectMake(60,170,200,80);
    CGContextAddRect(context, rectangle);
    CGContextStrokePath(context);

但我找不到如何将其添加到特定视图或视图中心。

4

2 回答 2

4

您提供的绘图代码需要放在其 drawRect 方法中的自定义 UIView 子类中。

但是,如果您只是想在屏幕上的某处显示一个矩形,则只需添加所需大小的子视图并相应地设置其图层属性会更容易:

#import <QuartzCore/QuartzCore.h>
//...
UIView *rectView = [[UIView alloc] initWithFrame:CGRectMake(60,170,200,80)];
rectView.backgroundColor = [UIColor clearColor];
rectView.layer.borderColor = [[UIColor blueColor] CGColor];
rectView.layer.borderWidth = 2.0;
[someView addSubview:rectView];
于 2012-10-23T19:00:37.277 回答
3

I think you probably want to subclass the UIView in question and override its drawRect:

- (void)drawRect:(CGRect)rect

be sure to call:

[super drawRect:rect];

Then you want to use coordinates in your drawing code that are relative to the size of the view you are drawing in.

So you get something more like:

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2.0);
    CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
    CGFloat width = 200;
    CGFloat height = 80;
    CGFloat x = (self.frame.size.width - width) * 0.5f;
    CGFloat y = (self.frame.size.height - height) * 0.5f;
    CGRect rectangle = CGRectMake(x, y, width, height);
    CGContextAddRect(context, rectangle);
    CGContextStrokePath(context);
}
于 2012-10-23T19:12:23.147 回答