In my application i can draw a line in a UIImageView by the code below,and i want redraw the line even longer when i call the function,however,the output come out is not as expected,it will just draw a new line and remove the old one,the length is remain the same jus the y position different,i dont know which line of my code is wrong or i havent understand the CGContext class in correct way,please help i have scratch my head all the days and cannot find out the problem
- (void) drawLine {
lastPoint = currentPoint;
lastPoint.y -= 40;
//drawImage is a UIImageView declared at header
UIGraphicsBeginImageContext(drawImage.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, drawImage.frame.size.width, drawImage.frame.size.height)];
//sets the style for the endpoints of lines drawn in a graphics context
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetLineCap(ctx, kCGLineCapButt);
//sets the line width for a graphic context
CGContextSetLineWidth(ctx,2.0);
//set the line colour
CGContextSetRGBStrokeColor(ctx, 1.0, 0.0, 0.0, 1.0);
//creates a new empty path in a graphics context
CGContextBeginPath(ctx);
//begin a new path at the point you specify
CGContextMoveToPoint(ctx, currentPoint.x, currentPoint.y);
//Appends a straight line segment from the current point to the provided point
CGContextAddLineToPoint(ctx, currentPoint.x,lastPoint.y);
//paints a line along the current path
CGContextStrokePath(ctx);
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
currentPoint = lastPoint;
}
I am sure you are done with this, but you have a typo.
CGContextAddLineToPoint(ctx, currentPoint.x,lastPoint.y);
should be:
CGContextAddLineToPoint(ctx, lastPoint.x,lastPoint.y);
Related
I am creating a drawing app. One of the features is multicolour line drawing. It should work like user touch up the screen and leads on it drawing a line. Colour of the line changes smoothly. Like that http://www.examples.pavelgatilov.com/Screen%20Shot%202013-09-22%20at%208.37.42%20PM.png
I tried several approaches, but haven't been lucky.
My line drawing method is below:
- (void) drawLineFrom:(CGPoint)from to:(CGPoint)to width:(CGFloat)width
{
self.drawColor = toolColor;
UIGraphicsBeginImageContext(self.frame.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextScaleCTM(ctx, 1.0f, -1.0f);
CGContextTranslateCTM(ctx, 0.0f, -self.frame.size.height);
if (drawImage != nil) {
CGRect rect = CGRectMake(0.0f, 0.0f, self.frame.size.width, self.frame.size.height);
CGContextDrawImage(ctx, rect, drawImage.CGImage);
}
CGContextSetLineCap(ctx, kCGLineCapRound);
CGContextSetLineWidth(ctx, width);
CGContextSetStrokeColorWithColor(ctx, self.drawColor.CGColor);
CGContextMoveToPoint(ctx, from.x, from.y);
CGContextAddLineToPoint(ctx, to.x, to.y);
CGContextStrokePath(ctx);
CGContextFlush(ctx);
drawImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
drawLayer.contents = (id)drawImage.CGImage;
}
Thanks for your help
Depending on exactly what colours, how they change and what effect you want / what happens with turns in the line, you may want to look at some combination of:
CGContextDrawLinearGradient with masking to the users drawn path.
colorWithPatternImage:
CGContextDrawLinearGradient drawn behind another layer and drawing transparency into the top layer with kCGBlendModeClear
How to draw a line on the UIImageView? I am using the UIImageView Sub Class, Its not support drawRect: method. I want to draw a line on the image view. How can I do this? Please help me. I am using below code for draw line.
- (void)drawRect:(CGRect)rect {
CGContextRef c = UIGraphicsGetCurrentContext();
CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
CGContextSetStrokeColor(c, red);
CGContextBeginPath(c);
CGContextMoveToPoint(c, 5.0f, 5.0f);
CGContextAddLineToPoint(c, 50.0f, 50.0f);
CGContextStrokePath(c);
}
The following code works by creating a new image the same size as the original, drawing a copy of the original image onto the new image, then drawing a 1 pixel line along to the top of the new image.
// UIImage *originalImage = <the image you want to add a line to>
// UIColor *lineColor = <the color of the line>
UIGraphicsBeginImageContext(originalImage.size);
// Pass 1: Draw the original image as the background
[originalImage drawAtPoint:CGPointMake(0,0)];
// Pass 2: Draw the line on top of original image
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 1.0);
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, originalImage.size.width, 0);
CGContextSetStrokeColorWithColor(context, [lineColor CGColor]);
CGContextStrokePath(context);
// Create new image
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// Tidy up
UIGraphicsEndImageContext();
First, I wouldn't use a UIImageView. In fact the docs say...
If your subclass needs custom drawing code, it is recommended you use
UIView as the base class.
Use a UIView.
In the UIView add a UIImageView subView and put the image in there. Now you can do you custom drawing in the drawRect method of the UIView and it will appear on top of the image.
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextSetLineWidth(context, 5.0);
CGContextStrokeRect(context, self.bounds);
}
If this isn't working then the drawRect method probably isn't being called. Set a breakpoint to test it.
The best way to go about it in my opinion would be to take a invisible UIView of the same size as UIImageView for drawing and implement the touch methods on the UIView for drawing.
you can use something like:
CGPoint temp=[touch locationInView:self];
Use this in methods like:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
Store all the points in an array and then draw those points on the UIImageView as it is.
Refer to Muhammad Saad Ansari
With Swift
func drawLines ( originalImage:UIImage, lineColor:CGColor ) -> UIImage{
UIGraphicsBeginImageContextWithOptions(originalImage.size,false,0.0)
originalImage.drawInRect(CGRectMake( 0, 0, originalImage.size.width, originalImage.size.height ))
let context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 5.0);
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, originalImage.size.width, 0);
CGContextSetStrokeColorWithColor(context,lineColor);
CGContextStrokePath(context);
// Create new image
var newImage = UIGraphicsGetImageFromCurrentImageContext();
// Tidy up
UIGraphicsEndImageContext();
return newImage
}
I am trying to draw a straight line between two points in overlay view.
In MKOverlayView method, I think I am doing correctly but I don't understand why it's not drawing any lines...
Does anyone know why?
- (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale
inContext:(CGContextRef)context
{
UIGraphicsPushContext(context);
MKMapRect theMapRect = [[self overlay] boundingMapRect];
CGRect theRect = [self rectForMapRect:theMapRect];
// Clip the context to the bounding rectangle.
CGContextAddRect(context, theRect);
CGContextClip(context);
CGPoint startP = {theMapRect.origin.x, theMapRect.origin.y};
CGPoint endP = {theMapRect.origin.x + theMapRect.size.width,
theMapRect.origin.y + theMapRect.size.height};
CGContextSetLineWidth(context, 3.0);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextBeginPath(context);
CGContextMoveToPoint(context, startP.x, startP.y);
CGContextAddLineToPoint(context, endP.x, endP.y);
CGContextStrokePath(context);
UIGraphicsPopContext();
}
Thank you for your help.
The line is being drawn using startP and endP which are CGPoint values but they are initialized using theMapRect which contains MKMapPoint values.
Instead, initialize them using theRect which you are converting from theMapRect using rectForMapRect.
Also, for the line width, you may want to scale it using the MKRoadWidthAtZoomScale function. Otherwise, a fixed line width of 3.0 will not be visible unless you are zoomed in very close.
The changed code would look like this:
CGPoint startP = {theRect.origin.x, theRect.origin.y};
CGPoint endP = {theRect.origin.x + theRect.size.width,
theRect.origin.y + theRect.size.height};
CGContextSetLineWidth(context, 3.0 * MKRoadWidthAtZoomScale(zoomScale));
Finally, instead of a custom MKOverlayView, why not use a MKPolylineView to avoid drawing lines manually?
I am trying to make an iPhone application with erasing. I am running into 2 problems, if you have a solution for either one please answer this. I would like to erase part of an image.
1) I am currently just clearing the rect but it has a square edge. I would like it to be round, I have previously tried translating but this does not work. I also need it to translate/rotate as few times as possible to maintain the same performance.
2) In addition I wanted to know if there are any other ways of erasing. When erasing fast it is erasing ever 1/2 inch. Is there a way to stroke a path and clear the rect or something? Sorry if this is hard to understand.
CGRect circleRect = CGRectMake([touch CGPointValue].x, [touch CGPointValue].y, 25, 25);
CGContextClearRect(currentContext,circleRect);
This code should do what you're looking for:
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, self.strokeWidth);
CGContextSetBlendMode(context, kCGBlendModeClear);
CGContextSetStrokeColorWithColor(context, [[UIColor clearColor] CGColor]);
CGContextBeginPath(context);
CGContextMoveToPoint(context, lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(context, currentPoint.x, currentPoint.y);
CGContextStrokePath(context);
CGContextFlush(context);
The key points are
1) CGContextSetLineCap(context, kCGLineCapRound), which makes it round
2) CGContextSetBlendMode(context, kCGBlendModeClear) which clears the context.
I realize this is an older question but I thought I would expand on Eric Reids answer as I was trying to use his example outside of the drawRect method and had to modify it to get it to work with a context I created in a 'touchesMoved' method in a UIView subclass.
I call this method from 'touchesMoved' and pass it the CGPoint of the touch in the view I'm drawing in.
-(void) processEraseAtPoint:(CGPoint)point
{
// setup a context with the size of our canvas view (the canvas view is the UIView instance I'm drawing into)
UIGraphicsBeginImageContext(self.canvasView.bounds.size);
// get a reference to the context we just created
CGContextRef context = UIGraphicsGetCurrentContext();
// draw the image we want to edit into this context (this is the image containing the drawing I want to erase part of)
[self.canvasView.incrementalImage drawAtPoint:CGPointZero];
// set our context options
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, self.canvasView.settings.brushDiameter);
CGContextSetBlendMode(context, kCGBlendModeClear);
// make the color clear since we're erasing
CGContextSetStrokeColorWithColor(context, [[UIColor clearColor] CGColor]);
// start our path in this context
CGContextBeginPath(context);
// set our first point
CGContextMoveToPoint(context, lastTouch.x, lastTouch.y);
// draw from our last point to this point
CGContextAddLineToPoint(context, point.x, point.y);
// stroke this path (in this case it's clear so it will erase what's there)
CGContextStrokePath(context);
// set our incrementalImage in the canvasView with the updated image from this context
// Note that in the canvasView 'drawRect' method I am calling
// '[self.incrementalImage drawInRect:rect]', so this new image will get drawn
// in my canvasView when I call 'setNeedsDisplay'
self.canvasView.incrementalImage = UIGraphicsGetImageFromCurrentImageContext();
// cleanup our context
CGContextFlush(context);
UIGraphicsEndImageContext();
// set our last touch point for the next line segment
lastTouch = point;
// update our view
[self.canvasView setNeedsDisplay];
}
I am having some troubles using the CGContext with an iPhone app. I am trying to draw several lines with different colors, but all the lines always end up having the color which was used last. I tried several approaches, but haven't been lucky.
I set up a small sample project to deal with that issue. This is my code, I use in the drawRect method. I am trying to draw a red and a blue line:
- (void)drawRect:(CGRect)rect{
NSLog(#"drawrect!");
CGContextRef bluecontext = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(bluecontext, 2.0);
CGContextSetStrokeColorWithColor(bluecontext, [UIColor blueColor].CGColor);
CGContextMoveToPoint(bluecontext, 1, 1);
CGContextAddLineToPoint(bluecontext, 100, 100);
CGContextSetStrokeColorWithColor(bluecontext, [UIColor redColor].CGColor);
CGContextAddLineToPoint(bluecontext, 200, 100);
CGContextStrokePath(bluecontext);
}
thanks for your help
Insert this code just before you set the stroke color the second time:
CGContextStrokePath(bluecontext);
CGContextBeginPath(bluecontext);
All the AddLine and AddOther calls are building a path. The path is drawn with a call like StrokePath, using the most recently set colors and other attributes. You are trying to draw two separate paths, so you must call Begin and Stroke for each path. Begin is sort of implicit when you start drawing, although it does not hurt to call it yourself. The basic flow of drawing is:
CGContextBeginPath(bluecontext); // clears any previous path
// add lines, curves, rectangles, etc...
CGContextStrokePath(bluecontext); // renders the path
Thats what you need.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, rect);
CGContextSetLineWidth(context, 2.0);
CGContextBeginPath(context);
CGContextSetStrokeColorWithColor(context, [UIColor orangeColor].CGColor);
CGContextMoveToPoint(context, 1, 1);
CGContextAddLineToPoint(context, 100, 100);
CGContextStrokePath(context); // and draw orange line}
CGContextBeginPath(context);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextMoveToPoint(context, 100, 100);
CGContextAddLineToPoint(context, 200, 100);
CGContextStrokePath(context); // draw blue line
I think this could be working.
CGContextRef bluecontext = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(bluecontext, 2.0);
CGContextSetStrokeColorWithColor(bluecontext, [UIColor blueColor].CGColor);
CGContextMoveToPoint(bluecontext, 1, 1);
CGContextAddLineToPoint(bluecontext, 100, 100);
CGContextStrokePath(bluecontext); // draw blue line
CGContextSetStrokeColorWithColor(bluecontext, [UIColor redColor].CGColor);
CGContextAddLineToPoint(bluecontext, 200, 100);
CGContextStrokePath(bluecontext); // and draw red line
If you are interested in the way it looks in a loop:
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGPoint startingPoint = [[pointsArray objectAtIndex:0] CGPointValue];
CGContextMoveToPoint(context, startingPoint.x, startingPoint.y); //start at this point
for (int i = 1; i < [pointsArray count]; i++) {
CGContextBeginPath(context);
//start at the previous point
CGContextMoveToPoint(context,
[[pointsArray objectAtIndex:i-1] CGPointValue].x,
[[pointsArray objectAtIndex:i-1] CGPointValue].y);
CGPoint point = [[pointsArray objectAtIndex:i] CGPointValue];
if (point.y < 50) { // if y is less then 50 use red color
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
} else { // else use blue color
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
}
CGContextAddLineToPoint(context, point.x, point.y); //draw to this point
CGContextStrokePath(context);
}
}