【问题标题】:Draw line in UIView在 UIView 中画线
【发布时间】:2011-03-08 21:50:43
【问题描述】:

我需要在 UIView 中画一条水平线。什么是最简单的方法。例如,我想在 y-coord=200 处画一条黑色水平线。

我没有使用界面生成器。

【问题讨论】:

标签: ios iphone uiview


【解决方案1】:

斯威夫特 3、4、5

这是我能找到的最简单的...

let lineView = UIView(frame: CGRect(x: 4, y: 50, width: self.view.frame.width, height: 1))
lineView.backgroundColor = .lightGray
self.view.addSubview(lineView)

【讨论】:

    【解决方案2】:

    斯威夫特 3 和斯威夫特 4

    这就是您如何在视图末尾绘制一条灰线(与 b123400 的答案相同)

    class CustomView: UIView {
    
        override func draw(_ rect: CGRect) {
            super.draw(rect)
            
            if let context = UIGraphicsGetCurrentContext() {
                context.setStrokeColor(UIColor.gray.cgColor)
                context.setLineWidth(1)
                context.move(to: CGPoint(x: 0, y: bounds.height))
                context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
                context.strokePath()
            }
        }
    }
    

    【讨论】:

    • 从 viewDidLayoutSubviews 调用“if let context”失败。
    【解决方案3】:

    添加不带文字的标签,背景颜色对应帧大小(例如:高度=1)。通过代码或在界面生成器中完成。

    【讨论】:

      【解决方案4】:

      根据 Guy Daher 的回答。

      我尽量避免使用 ?因为如果 GetCurrentContext() 返回 nil 会导致应用程序崩溃。

      我会做 nil 检查 if 语句:

      class CustomView: UIView 
      {    
          override func draw(_ rect: CGRect) 
          {
              super.draw(rect)
              if let context = UIGraphicsGetCurrentContext()
              {
                  context.setStrokeColor(UIColor.gray.cgColor)
                  context.setLineWidth(1)
                  context.move(to: CGPoint(x: 0, y: bounds.height))
                  context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
                  context.strokePath()
              }
          }
      }
      

      【讨论】:

      • 如果 if 子句的原因只是为了从可选中取消框,请改用 guard 语句。
      【解决方案5】:

      在您的情况下(水平线)最简单的方法是添加具有黑色背景颜色和框架[0, 200, 320, 1] 的子视图。

      代码示例(希望没有错误——我是在没有 Xcode 的情况下编写的):

      UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 200, self.view.bounds.size.width, 1)];
      lineView.backgroundColor = [UIColor blackColor];
      [self.view addSubview:lineView];
      [lineView release];
      // You might also keep a reference to this view 
      // if you are about to change its coordinates.
      // Just create a member and a property for this...
      

      另一种方法是创建一个类,该类将在其 drawRect 方法中绘制一条线(您可以查看我的代码示例here)。

      【讨论】:

      • 在 Storyboard 中无需任何代码即可执行此操作。它更容易更好。
      • @coolcool1994,你没注意到“我没有使用 Interface Builder”。问题中的要求?
      【解决方案6】:

      也许这有点晚了,但我想补充一点,有更好的方法。 使用 UIView 很简单,但相对较慢。此方法覆盖视图如何绘制自身并且速度更快:

      - (void)drawRect:(CGRect)rect {
          [super drawRect:rect];
      
          CGContextRef context = UIGraphicsGetCurrentContext();
          CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
      
          // Draw them with a 2.0 stroke width so they are a bit more visible.
          CGContextSetLineWidth(context, 2.0f);
      
          CGContextMoveToPoint(context, 0.0f, 0.0f); //start at this point
      
          CGContextAddLineToPoint(context, 20.0f, 20.0f); //draw to this point
      
          // and now draw the Path!
          CGContextStrokePath(context);
      }
      

      【讨论】:

      • 如果在 UIView 中使用此代码,此示例中的坐标是相对于视图边界还是整个屏幕?
      • CGContextMoveToPoint(...);之前不需要调用CGContextBeginPath(context);吗?
      • 使用视图来做这件事并不太可怕。它使事情变得更容易,例如,在方向更改期间执行隐式动画时。如果只是一个,另一个 UIView 也不会那么昂贵,代码也简单得多。
      • 此外,您还可以使用以下代码获取边界和中点:CGPoint midPoint; midPoint.x = self.bounds.size.width / 2; midPoint.y = self.bounds.size.height / 2;
      • 对,它“慢”的评论是不明智的。屏幕上随时都有大量简单的 UIView。请注意,绘制一个 (!) 文本字符,以及涉及的所有处理,会淹没绘制填充的 UIView。
      【解决方案7】:

      另一种(甚至更短的)可能性。如果你在 drawRect 里面,像下面这样:

      [[UIColor blackColor] setFill];
      UIRectFill((CGRect){0,200,rect.size.width,1});
      

      【讨论】:

        【解决方案8】:

        您可以为此使用 UIBezierPath 类:

        并且可以画任意多的线条:

        我已经继承了 UIView :

            @interface MyLineDrawingView()
            {
               NSMutableArray *pathArray;
               NSMutableDictionary *dict_path;
               CGPoint startPoint, endPoint;
            }
        
               @property (nonatomic,retain)   UIBezierPath *myPath;
            @end
        

        并初始化了用于画线的 pathArray 和 dictPAth 对象。我正在从我自己的项目中编写代码的主要部分:

        - (void)drawRect:(CGRect)rect
        {
        
            for(NSDictionary *_pathDict in pathArray)
            {
                [((UIColor *)[_pathDict valueForKey:@"color"]) setStroke]; // this method will choose the color from the receiver color object (in this case this object is :strokeColor)
                [[_pathDict valueForKey:@"path"] strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
            }
        
            [[dict_path objectForKey:@"color"] setStroke]; // this method will choose the color from the receiver color object (in this case this object is :strokeColor)
            [[dict_path objectForKey:@"path"] strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
        
        }
        

        touchesBegin 方法:

        UITouch *touch = [touches anyObject];
        startPoint = [touch locationInView:self];
        myPath=[[UIBezierPath alloc]init];
        myPath.lineWidth = currentSliderValue*2;
        dict_path = [[NSMutableDictionary alloc] init];
        

        touchesMoved 方法:

        UITouch *touch = [touches anyObject];
        endPoint = [touch locationInView:self];
        
         [myPath removeAllPoints];
                [dict_path removeAllObjects];// remove prev object in dict (this dict is used for current drawing, All past drawings are managed by pathArry)
        
            // actual drawing
            [myPath moveToPoint:startPoint];
            [myPath addLineToPoint:endPoint];
        
            [dict_path setValue:myPath forKey:@"path"];
            [dict_path setValue:strokeColor forKey:@"color"];
        
            //                NSDictionary *tempDict = [NSDictionary dictionaryWithDictionary:dict_path];
            //                [pathArray addObject:tempDict];
            //                [dict_path removeAllObjects];
            [self setNeedsDisplay];
        

        touchesEnded 方法:

                NSDictionary *tempDict = [NSDictionary dictionaryWithDictionary:dict_path];
                [pathArray addObject:tempDict];
                [dict_path removeAllObjects];
                [self setNeedsDisplay];
        

        【讨论】:

          【解决方案9】:

          只需添加一个没有文字和背景颜色的标签。 设置您选择的坐标以及高度和宽度。 您可以手动完成,也可以使用 Interface Builder。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-09-22
            • 1970-01-01
            • 2011-07-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-04-09
            • 1970-01-01
            相关资源
            最近更新 更多