Draw line in UIView

后端 未结 8 838
粉色の甜心
粉色の甜心 2020-12-02 05:52

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.

I am NOT using In

8条回答
  •  渐次进展
    2020-12-02 06:18

    You can user UIBezierPath Class for this:

    And can draw as many lines as you want:

    I have subclassed 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:

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

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

    touchesMoved Method:

    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:

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

提交回复
热议问题