Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw Line using CGContext

I want to draw line in table view cell so that I can place textfield & switch in single cell. I increased the height of cell. How can I draw line in cell?

I have subclass of UIView which contains following code

 //Get the CGContext from this view
 CGContextRef context = UIGraphicsGetCurrentContext();
 //Set the stroke (pen) color
 CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
 //Set the width of the pen mark
 CGContextSetLineWidth(context, 1.0);

 // Draw a line
 //Start at this point
 CGContextMoveToPoint(context, 10.0, 30.0);

 //Give instructions to the CGContext
 //(move "pen" around the screen)
 CGContextAddLineToPoint(context, 310.0, 30.0);


 //Draw it
 CGContextStrokePath(context);

Then I have a tableViewController with grouped table style. In cellForRowAtIndexPath I have following code

//code to add textfield
DrawLineView *drawLine = [[DrawLineView alloc]init];
[cell addSubview:drawLine];
//code add switch

But it is not drawing any line. I can't use 2 different cells. I have to Please help me. This is my first to deal with graphics i iphone. Thanks

like image 987
iOSAppDev Avatar asked Mar 20 '11 18:03

iOSAppDev


People also ask

How do you draw a line in Swift?

To draw a line from the current point to a specific point, you call the addLine(to:) method. By default, iOS fills the path with the default foreground color, which is black.

What is CGContext in Swift?

The CGContext type represents a Quartz 2D drawing destination. A graphics context contains drawing parameters and all device-specific information needed to render the paint on a page to the destination, whether the destination is a window in an application, a bitmap image, a PDF document, or a printer.


1 Answers

If all you want to do is draw a line, it would be a lot better to use a CAShapeLayer, pass it a path with a line, and then attach that as a sublayer of the cells content view. The table should perform better than using a view with a custom drawRect.

Example of drawing a line via CALayer and a path:

// You'll also need the QuartzCore framework added to the project
#import <QuartzCore/QuartzCore.h>

CAShapeLayer *lineShape = nil;
CGMutablePathRef linePath = nil;
linePath = CGPathCreateMutable();
lineShape = [CAShapeLayer layer];

lineShape.lineWidth = 4.0f;
lineShape.lineCap = kCALineCapRound;;
lineShape.strokeColor = [[UIColor blackColor] CGColor];

int x = 0; int y = 0;
int toX = 30; int toY = 40;                            
CGPathMoveToPoint(linePath, NULL, x, y);
CGPathAddLineToPoint(linePath, NULL, toX, toY);

lineShape.path = linePath;
CGPathRelease(linePath);
[self.layer addSublayer:lineShape];
like image 77
Kendall Helmstetter Gelner Avatar answered Sep 30 '22 19:09

Kendall Helmstetter Gelner