LineView

It’s surprisingly tricky just to draw a single line in iOS. Quartz has great 2D graphic support, but you need to dive down into that world and use many lines of code to draw one line. In some cases, you really just want a few well-placed lines to augment an elegant UI – this class is designed to address that problem. You can add a line to your view with two lines of code. You can also get a transparent UIImage with just the line, which can be used in conjunction with UIImageView, image-processing functions, or image-related classed like WipeView to do more complex things with your lines.

This is a very easy-to-create class once you know Quartz, so there’s not much to explain. I just thought it would be useful, so I added it to moriarty (free to use, open source under Apache 2 license). I think the header file explains it pretty well:

//
//  LineView.h
//
//  Created by Tyler Neylon on 4/5/11.
//
//  View to draw a single line.
//
//  Sample usage:
//
//    CGPoint a = CGPointMake(10, 10);
//    CGPoint b = CGPointMake(50, 100);
//    LineView *lineView = [LineView lineFromPoint:a toPoint:b];
//    lineView.color = [UIColor blueColor];
//    [self.view addSubview:lineView];
//

#import <Foundation/Foundation.h>


@interface LineView : UIView {
 @private
  // strong
  UIColor *color;
 
  CGFloat lineWidth;
  CGPoint a;
  CGPoint b;
}

@property (nonatomic, retain) UIColor *color;
@property (nonatomic) CGFloat lineWidth;

+ (LineView *)lineFromPoint:(CGPoint)a toPoint:(CGPoint)b;

// The image will be transparent except for the line, and
// have padding around the line.  It will be sized so that,
// when placed with frameOrigin = (0,0), the line will have
// the coordinates given in the constructor.
- (UIImage *)getImage;

@end

2 Comments

  1. J
    Posted April 11, 2011 at 5:54 pm | Permalink

    Just dropping by to say that your blog posts are awesome! All the tips and snippets are very useful! Thanks for sharing and keep it on!=]

  2. Posted April 12, 2011 at 10:31 pm | Permalink

    Thanks @J!

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*