ios 在 UIView 中画线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3128752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:23:31  来源:igfitidea点击:

Draw line in UIView

iosiphoneuiview

提问by John Smith

I need to draw a horizontal line in a UIView. What is the easiest way to do it. For example, I want to draw a black horizontal line at y-coord=200.

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

I am NOT using Interface Builder.

我没有使用界面生成器。

回答by b123400

Maybe this is a bit late, but I want to add that there is a better way. Using UIView is simple, but relatively slow. This method overrides how the view draws itself and is faster:

也许这有点晚了,但我想补充一点,有更好的方法。使用 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);
}

回答by Michael Kessler

The easiest way in your case (horizontal line) is to add a subview with black background color and frame [0, 200, 320, 1].

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

Code sample (I hope there are no errors - I wrote it without Xcode):

代码示例(我希望没有错误 - 我在没有 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...

Another way is to create a class that will draw a line in its drawRect method (you can see my code sample for this here).

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

回答by Guy Daher

Swift 3 and Swift 4

斯威夫特 3 和斯威夫特 4

This is how you can draw a gray line at the end of your view (same idea as b123400's answer)

这就是如何在视图的末尾绘制一条灰线(与 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()
        }
    }
}

回答by Phanindra

Just add a Label without text and with background color. Set the Coordinates of your choice and also height and width. You can do it manually or with Interface Builder.

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

回答by Rakesh

You can user UIBezierPath Class for this:

您可以为此使用 UIBezierPath 类:

And can draw as many lines as you want:

并且可以根据需要绘制任意数量的线:

I have subclassed UIView :

我有子类 UIView :

    @interface MyLineDrawingView()
    {
       NSMutableArray *pathArray;
       NSMutableDictionary *dict_path;
       CGPoint startPoint, endPoint;
    }

       @property (nonatomic,retain)   UIBezierPath *myPath;
    @end

And initialized the pathArray and dictPAth objects which will be used for line drawing. I am writing the main portion of the code from my own project:

并初始化了用于画线的 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 method :

touchesBegin 方法:

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

touchesMoved Method:

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 Method:

touchesEnded 方法:

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

回答by hkatz

One other (and an even shorter) possibility. If you're inside drawRect, something like the following:

另一种(甚至更短的)可能性。如果您在 drawRect 中,则类似于以下内容:

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

回答by Robert Harrold

Based on Guy Daher's answer.

基于 Guy Daher 的回答。

I try to avoid using ? because it can cause an application crash if the GetCurrentContext() returns nil.

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

I would do nil check if statement:

我会做 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()
        }
    }
}

回答by Reddy

Add label without text and with background color corresponding frame size(ex:height=1). Do it through code or in interface builder.

添加不带文本和背景颜色对应框架大小的标签(例如:高度 = 1)。通过代码或在界面构建器中完成。