I'm trying to implement "hand draw tool".
At the moment algorythm looks like that (I don't insert any code because methods are quite big, will try to explain an idea):
Drawing
In touchesStarted: method I create NSMutableArray *pointsArray and add point into it. Call setNeedsDisplay: method.
In touchesMoved: method I calculate points between last added point from the pointsArray and current point. Add all points to the pointsArray. Call setNeedsDisplay: method.
In touchesFinished: event I calculate points between last added point from the array and current point. Set flag touchesWereFinished. Call setNeedsDisplay:.
Render:
drawRect: method checks is pointsArray != nil and is there any data in it. If there is - it starts to traw circles in each point of this array. If flag touchesWereFinished is set - save current context to the UIImage, release pointsArray, set it to nil and reset the flag.
There are a lot disadvantages of this method:
It is slow
It becomes extremely slow when user touches and move finger for long time. Array becomes enormous
"Lines" composed by circles are ugly
I would like to change my algorithm to make it bit faster and line smoother.
In result I would like to have lines like on the picture at following URL (sorry, not enough reputation to insert an image): http://2.bp.blogspot.com/_r5VzEAUYXJ4/SrOYp8tJCPI/AAAAAAAAAMw/ZwDKXiHlhV0/s320/SketchBook+Mobile(4).png
Can you advice me, ho I can draw lines this way (smooth and slim on the edges)? I thought to draw circles with alpha gradient on the edges (to make lines smoother), but it will be extremely slowly IMHO.
Thanks for help
Update
I changed draw algorithm. Now every event I save UITouch and in the drawRect: method I draw path from prev. point to the current one. And dump UIImage from context every drawRect: invocation.
But I still have 2 questions:
Is it possible to draw more smooth. I mean if I draw quite fast, I easily can see that path path is a set of straight lines. But I want to draw curves, to make path smooth. Probably Bezier curves will help but I don't understand how they can help in this.
situation.
I want to start path with thiner line and finish with thiner line too. How I can do this line transform?
Thanks!
Related
I've got an image that's allowed to be rotated and scaled by the user.
Every time the user clicks the image I try to figure out if the point is transparent or not.
If it's transparent I return null in my view's HitTest, if it's not transparent I return the view. Problems start when user rotates the image. In my hitTest method, I need to transform the point according to the current view's rotation. Otherwise the point will indicate an irrelevant location on the view (and the image).
How do I do that?
Thank you very much.
This CGAffineTransform Reference might help:
CGPointApplyAffineTransform
CGRectApplyAffineTransform
and
CGSizeApplyAffineTransform
But before you start thinking that you need to perform the mapping by hand, I would suggest to give it a try 'as if' the current transformation was CGAffineIdentity, and code your coordinate detection accordingly. You might be surprised by the results ...
My own experience says that it looks like when you get your points from UITouch locationIn_SomeView_ the inverted matrix of SomeView is applied to the point before it is handed back to you.
So, you probably don't need any of the CGxxxApplyAffineTransform unless you generate the points yourself, outside of the events system.
How would I efficiently draw a CGPath on a CATiledLayer? I'm currently checking if the bounding box of the tile intersects the bounding box of the path like this:
-(void)drawLayer:(CALayer*)layer inContext:(CGContextRef)context {
CGRect boundingBox = CGPathGetPathBoundingBox(drawPath);
CGRect rect = CGContextGetClipBoundingBox(context);
if( !CGRectIntersectsRect(boundingBox, rect) )
return;
// Draw path...
}
This is not very efficient as the drawLayer:inContext: is called multiple times from multiple threads and results in drawing the path many times.
Is there a better, more efficient way to do this?
The simplest option is to draw your curve into a large image and then tile the image. But if you're tiling, it probably means the image would be too large, or you would have just drawn the path in the first place, right?
So you probably need to split your path up. The simplest approach is to split it up element by element using CGPathApply. For each element, you can check its bounding box and determine if that element falls in your bounds. If not, just keep track of the last end point. If so, then move to the last end point you saw and add the element to a new path for this tile. When you're done, each tile will draw its own path.
Technically you will "draw" things that go outside your bounds here (such as a line that extends beyond the tile), but this is much cheaper than it sounds. Core Graphics is going to clip single elements very easily. The goal is to avoid calculating elements that are not in your bounding box at all.
Be sure to cache the resulting path. You don't need to calculate the path for every tile; just the ones you're drawing. But avoid recalculating it every time the tile draws. Whenever the data changes, dump your cache. If there are a very large number of tiles, you can also use NSCache to optimize this even better.
You don't show where the path gets created. If possible, you might try building the path up in the -drawLayer:inContext: method, only creating the portion of it needed for the tile being drawn.
As with all performance problems, you should use Instruments to profile your code and find out exactly where the bottlenecks are. Have you tried that already, and if so, what did you find?
As a side note, is there a reason you're using CGPath instead of UIBezierPath? From Apple's documentation:
For creating paths in iOS, it is recommended that you use UIBezierPath
instead of CGPath functions unless you need some of the capabilities
that only Core Graphics provides, such as adding ellipses to paths.
For more on creating and rendering paths in UIKit, see “Drawing Shapes
Using Bezier Paths.”
When I'm using a UIBezierPath to draw where the user is touching if the user moves to fast sometimes I get really hard points like the tip of a triangle. Any clue what might be causing this? Or how I can fix it?
I am capturing the points using touchesBegan/Moved/Ended and placing them into an NSArray of UIBezierPaths.
Despite the name, UIBezierPath doesn't just draw curves. In fact, by default it won't - presumably you're simply passing the coordinates returned by touchesBegan etc, into the addLineToPoint method.
Instead of simply passing all the touch coordinates directly into a UIBezierPath you should first interpolate them to avoid these sharp lines that occur when you rapidly move your finger across the screen. This is not too difficult, although does require some knowledge of how bezier curves work and spline interpolation.
If you are looking for a slightly easier way out, there are a couple of open source libraries that will do this for you, like this one: http://cocoacontrols.com/platforms/ios/controls/smooth-line-view
I have a NSArray of points that make up a path. I can detect when it self-intersects. When this happens, I try to fill the path.
First I used CoreGraphics, now I'm using openGl to draw a triangle array. Doesn't work well as you can see in the image.
How do I fill only the circular area while leaving the "tail" alone? I was thinking of a reverse flood fill but don't think CG has any API functions for this...
Maybe instead of actually drawing the path you can just approximate the diameter of the path and draw a circle with your approximation.
Here is some code to detect a circle gesture on the iPhone:
http://www.mobileorchard.com/iphone-circle-gesture-detection/
Record all of the points in a doubly-linked list. When it comes time to fill, walk the list from the start and find the point that's closest to the end. Then, lineto that point, then lineto each point in reverse order, stopping with the second point in the list. The fill will implicitly close the path, which will jump from where you left off (the second point) back to the start (first) point.
This is just off the top of my head; you can play with a couple of variations on this to see what works best. You might record the closest previous node in each node, but this could get expensive for many nodes.
I am making a simple iPhone drawing program as a personal side-project.
I capture touches event in a subclassed UIView and render the actual stuff to a seperate CGLayer. After each render, I call [self setNeedsLayout] and in the drawRect: method I draw the CGLayer to the screen context.
This all works great and performs decently for drawing rectangles. However, I just want a simple "freehand" mode like a lot of other iPhone applications have.
The way I thought to do this was to create a CGMutablePath, and simply:
CGMutablePathRef path;
-(void)touchBegan {
path = CGMutablePathCreate();
}
-(void)touchMoved {
CGPathMoveToPoint(path,NULL,x,y);
CGPathAddLineToPoint(path,NULL,x,y);
}
-(void)drawRect:(CGContextRef)context {
CGContextBeginPath(context);
CGContextAddPath(context,path);
CGContextStrokePath(context);
}
However, after drawing for more than 1 second, performance degrades miserably.
I would just draw each line into the off-screen CGLayer, if it were not for variable opacity! The less-than-100% opacity causes dots to be left on the screen connecting the lines. I have looked at CGContextSetBlendingMode() but alas I cannot find an answer.
Can anyone point me in the right direction? Other iPhone apps are able to do this with very good efficiency.
The problem is that with CGStrokePath() the current mutable path gets closed and drawn and a new path is created when you move your finger. So you probably end up with a lot of paths for one touch "session", at least that's what your pseudocode seems to do.
You can try to begin a new mutable path when touches begin, use CGAddLineToPoint() when the touches move und end the path when touches end (much like your pseudocode shows). But in the draw method, you draw a copy of the current mutable path, and the actual mutable path is still being elongated until the touches end, so you only get one path for the whole touch session. After the touches end you can add the path permanently - you can for example put all paths into an array and iterate over them in the draw method.
What SanHolo said - plus you may want to throttle the adding of points, so it only adds a new point no more often than every 10ms, say (you'd need to play with the interval). You can do that with a simple timer.
Also, how are you instructing the view that it needs to redraw itself? You might want to throttle that too - and it could be on a longer interval than the point capturing (e.g. capture points no more than every 10ms, and redraw no more often than every 200ms - again you'd need to play with the numbers).
In both cases you'd need to make sure that, if nothing happens for longer than the interval the last point is captured, or the redraw is requested. That's where the timer comes in.