【问题标题】:drawing rectangle on existing uiview issue在现有的 uiview 问题上绘制矩形
【发布时间】:2012-06-15 20:40:30
【问题描述】:

我有一个基于视图控制器的应用程序,其中包含我根据某些逻辑显示/隐藏的多个视图。我想绘制一个与 UIView 大小相同的矩形,以使其像框架/边框形状。

我在绘制矩形时遇到问题。我知道下面的代码应该这样做,但我不确定为什么没有调用或触发这个方法。我也没有在任何地方看到生成的 (void)drawRect:(CGRect)rect 方法,所以我自己放置了它。不知道我在这里缺少什么..

- (void)drawRect:(CGRect)rect;
{   
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetRGBStrokeColor(context, 1.0, 1.0, 0.0, 1.0); // yellow line

    CGContextBeginPath(context);

    CGContextMoveToPoint(context, 50.0, 50.0); //start point
    CGContextAddLineToPoint(context, 250.0, 100.0);
    CGContextAddLineToPoint(context, 250.0, 350.0);
    CGContextAddLineToPoint(context, 50.0, 350.0); // end path

    CGContextClosePath(context); // close path

    CGContextSetLineWidth(context, 8.0); // this is set from now on until you explicitly change it

    CGContextStrokePath(context); // do actual stroking

    CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 0.5); // green color, half transparent
    CGContextFillRect(context, CGRectMake(20.0, 250.0, 128.0, 128.0)); // a square at the bottom left-hand corner
}

【问题讨论】:

  • drawRect: 是 UIView 上的一个方法,所以你是把这段代码放在视图控制器中还是继承了 UIView?
  • @Brian,我把它放在了视图控制器中。 UIView 的子类是什么意思,目的是什么?谢谢。

标签: objective-c ios4 xcode4.2


【解决方案1】:

如果您只需要添加一个简单的矩形边框,只需在您的 viewWillAppear: 中为您的视图控制器执行以下操作。

- (void) viewWillAppear:(BOOL)animated
{
   //Simple border on the main view
   self.view.layer.borderColor = [UIColor redColor].CGColor;
   self.view.layer.borderWidth = 2;

   //Or a simple rectangle to place at x,h within the main view 
   UIView *test = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
   test.backgroundColor = [UIColor redColor];
   [self.view addSubview:test];
}

希望这会有所帮助!

【讨论】:

  • 谢谢。我添加了 self.view.layer.cornerRadius = 10.0f;创建圆角,它做得很好,但是它在圆角后面显示白色背景,而我的 uiview 背景是黑色的。知道为什么在显示角落时显示此白色背景吗?
  • 您确定要在主视图上添加圆形边框吗?如果是这样,也许最好将 self.view 的背景颜色设置为您希望角落的颜色,然后添加另一个带有圆角的 UIView(如上面的示例代码)。
【解决方案2】:

只是猜测,但您是否告诉 UIView 重新显示自己?

[myUIView setNeedsDisplay];

只有这样drawRect: 才会被调用。

【讨论】:

    【解决方案3】:

    首先创建一个类(YourView),它是UIView 的子类。您在 viewController 中实现代码。

    - (void)viewDidLoad
    {
       YourView *temp = [[YourView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    
        [self.view addSubview:temp];
    }
    

    您将方法(- (void)drawRect:(CGRect)rect)写入YourView.m 文件。 像这样试试。我想对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-01
      相关资源
      最近更新 更多