iPhone Core Graphics thicker dashed line for subview - iphone

I have a UIView and within it I've drawn a line using Core Graphics by overriding drawRect. This view also contains one subview which also draws a line. However, whilst both views are using pretty much the same code (for testing purposes at least), the lines drawn on them do not appear the same:
As you can see - the dashed line at the top is noticeably thicker than the bottom one and I have no idea why. Below is the code used by the two UIViews in their drawRect methods. If you have any idea why this is happening then I'd appreciate your help and advice!
First View:
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [[UIColor whiteColor] CGColor]);
CGFloat dashes[] = {1,1};
CGContextSetLineDash(context, 0.0, dashes, 2);
CGContextSetLineWidth(context, 0.6);
CGContextMoveToPoint(context, CGRectGetMinX(rect), CGRectGetMaxY(rect));
CGContextAddLineToPoint(context, CGRectGetMaxX(rect), CGRectGetMaxY(rect));
CGContextStrokePath(context);
SubUIView *view = [[SubUIView alloc] initWithFrame:rect];
[self addSubview:view];
[view release];
The view is definitely only being drawn once. I appreciate drawRect may not be the best place for adding a subview but the problem remains even with it added in the main initWithFrame method.
Second View:
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [[UIColor whiteColor] CGColor]);
CGFloat dashes[] = {1,1};
CGContextSetLineDash(context, 0.0, dashes, 2);
CGContextSetLineWidth(context, 0.6);
CGContextMoveToPoint(context, CGRectGetMinX(rect), CGRectGetMidY(rect));
CGContextAddLineToPoint(context, CGRectGetMaxX(rect), CGRectGetMidY(rect));
CGContextStrokePath(context);

It could be a result of anti-aliasing if your rect does not fall on integers. You can disable anti-aliasing with CGContextSetShouldAntialias( context, NO ). I think there's also a function for making a rect integral, but I can't remember what it is.

First, you should fix the problem of the drawing code being WET*. You say you're doing this “for testing purposes”, but this actually makes testing harder, since you have to change both pieces of code and/or keep straight which version you're working on. The worst case is when you change both pieces of code in different ways and have to merge them by hand.
I'd say move the dashed-line code to the subview, add properties for anything the two pieces of code need to do differently, and create two subviews (and not in drawRect:—seriously).
As for the actual problem: Well, I don't see a big image, I see a tiny image, and I can only guess that the greater boldness of the upper line than that of the lower line means that the upper line is thicker.
By the way, the rect is not necessarily the bounds of your image. Don't ever assume that it is, or you will get funky drawing when it isn't. Assume that it some section of the bounds—possibly, but possibly not, the whole thing. When you mean [self bounds], say [self bounds].
The problem is most likely the difference between CGRectGetMidY([self bounds]) and CGRectGetMaxY([self bounds]). One includes a fraction that splits a pixel, whereas the other is a multiple of one pixel or close to it. (Not necessarily a multiple of 1—on a Retina Display, 1 pt = 2 pixels, so 1 pixel = 0.5 pt.) Try flooring both numbers and optionally adding 0.5, and see which way you like better.
There's no way to make it work out perfectly with a 0.6-pt line width. There is simply no whole number of pixels that works out to. All you can do is work out what looks best and do that.
*Written Elsewhere Too, the opposite of DRY.

Related

CoreGraphics - How do I draw rects one by one on a plane?

I have a sort of progress bar which is actually a visual representation of the read content of a book. This bar is a horizontal line which is filled up at areas the book was read at. As an example, if it's a 100 paged book, and the user has read only page 1 to 10 and 90 to 100, the progress bar will show the 10% area at the extreme left and 10% area at the extreme right filled with color.
I am currently using this code to draw rect for one reading session:
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect innerRect = CGRectInset(rect, 5, 5);
CGRect ProgressIndicator = CGRectMake(innerRect.origin.x, innerRect.origin.y, 20, innerRect.size.height);
CGContextSetStrokeColorWithColor(context, [[UIColor blueColor] CGColor]);
CGContextSetLineWidth(context, 5);
CGContextMoveToPoint(context, CGRectGetMinX(ProgressIndicator), CGRectGetMinY(ProgressIndicator));
CGContextAddLineToPoint(context, CGRectGetMaxX(ProgressIndicator), CGRectGetMinY(ProgressIndicator));
CGContextAddLineToPoint(context, CGRectGetMaxX(ProgressIndicator), CGRectGetMaxY(ProgressIndicator));
CGContextAddLineToPoint(context, CGRectGetMinX(ProgressIndicator), CGRectGetMaxY(ProgressIndicator));
CGContextClosePath(context);
CGContextStrokePath(context);
CGContextSetFillColorWithColor(context, [[UIColor blueColor]CGColor]);
CGContextFillRect(context, ProgressIndicator);
Now, this is just for one reading session and draws only one rect as the rectangular "read" portion on the bar. How do I manage the drawing if I have multiple rects (say in an array) to draw on the bar. I am afraid that I'll lose the current drawing once I draw another rect.
How do I use "for" loop to draw those multiple rects?
I know this might be a very dumb question but I tried finding a way around it but didn't succeed.
I'm going to suggest thinking about this a different way; keeping track of an arbitrary number of 'reading sessions' could be a very inefficient representation.
In situations like this rather than concatenating every time data from a 'reading session' I would suggest that a sparse representation might make your drawing easier - just keep track of which pages have been read, period, in an array or dictionary or a custom object.
Then, your drawing code could simply loop over the storage and draw a section in one color for 'read' and not draw, or draw another color, etc, for 'unread'.

How to create bubbles & arrows in iPhone help page about using buttons?

Most of the apps today provides the tutorial that teaches the user to how to use the buttons in the app. This help page is normally in black color with a little alpha value (so only the background will semi-visible) with a bubble box that contains the text to define controls and the arrow which points to the corresponding component.
Here is the sample image.. (From the app MyThings)
This is the normal page
And if you swipe from bottom to top, the help view will appear like..
Here is my doubts:
Which one is best to create the images & text in this help view? Drawing the images & texts using Core Graphics or by simply putting an UIImageView with a png image? Which one is efficient?
There is no problem in implementing a UIImageView with a ready-made png image. From my knowledge, the problem here is the image file size and the loading time. If we consider the drawing method, my mind things about the following problems.
Drawing a rectangle is so easy. (Refer here). But what about drawing a rectangle with a curved corners?? Is there any function available that handle this case?
Then the arrow, that points the corresponding component.. How can we find the exact point that should be pointed? (till iPhone 4S, there is no problem I hope, iPhone 5 has different height)
How to draw this pointers from the particular position in the rectangle?
Any ideas?
Just confused!!
Drawing the bubbles & arrows with CG is better, IMHO. It will work even if you change completely the app (if you draw them correctly pointing to the center of the button, for instance). With images, you'll need to have several copies for the different displays resolutions and scales. Also, you'll need to update the arrows if you change anything.
I don't see any performance drawback. Both methods will draw the bubbles very fast. Also, think that you can cache the CG generated images for future use.
See these questions to know how to draw bubbles:
How to draw a “speech bubble” on an iPhone?
How to make a Thought Bubble using core graphic in iPhone
It seems logical to use the center of the button each bubble point to. Your drawing methods needs to know where to point the arrow and the current orientation (if the app rotates). It should take into account other bubbles, to avoid overlap. You can divide the space in rows and columns and assign free space to each bubble.
For better user experience, those bubbles should not consume taps. If you tap a button when the bubbles are visible, the intended action should be performed (instead of just hiding the bubbles and require a second tap).
in your case i would refer resizable and reusable images.I also have many overlay screens in my app and i ended up wit generating 5 6 generic items arrows, label background and rectangular background image for the uilabel.
i know drawing rectangular is easy but it might be just overload sometimes.
if you want to change the direction of those arrows you can apply layer transformation to a UIImageview as following
arrowIamgeView.transform = CGAffineTransformMakeRotation(-M_PI / 20);
and for rounded corners of rectangles i assume you could user textfields with a certain background color and set their layers' cornerradius property.
Finally I did it!!
From my one-day experience, I come to know that there is three ways to handle this situation.
Simply creating needed images as png files and just use UIImageView to show. (But remember, you should have a same image with different resolutions. This will increase your app size).
Second way of doing is, Showing the bubbles (or maybe a rectangle) by creating labels, text fields, etc.. with a arrow image. You may simply transform the image to change the pointing place of the arrow. (As, Ilker Baltaci said in the previous answer).
Third way is, by Core Graphics. You can draw whatever you want here. As of my knowledge, increasing the app's size or increasing the memory consume by initializing/allocating/retaining labels & text fields, we can try this by Core Graphics.
I've three views where I want to implement this help screen facility. For just three screen, I can use any of the three method, because, there is no much difference related to performance if we use it for little-needed situaions. But I tried with the third way, because, I really don't knew anything about Core Graphics. So its just for learning..
Problems that I faced:
The arrow should point the center of the button(or maybe top of the button). So finding this exact location is complex. I have used this feature only in 3 pages in my app. Each page contains maximum of 4 icons to describe. So I just hard coded the values (My another luck is, the app does not support landscape mode). But, if you want to use this feature for so many pages, you should define some arrays and a method that finds the center of icons by calculating its center with reference to, their origin, height & width, blah, blah..
The another problem is, you should ensure that the bubbles are not overlapping anywhere. Here also, we need a global method that finds the location for each bubble. The size of the bubble depends on, the text size that is going to be placed inside it. This is more complex problem and for just 3 screens, I'm not going to define a global method with hundreds of calculations. So I again just hard coded the origin point, height & width of each bubble with reference to the self.view
Last but not least.. The Arrow!! The height of arrow may vary with the bubble's place. The width of the bubble also may vary with height. Also, you should know the side & points of the bubble from which the arrow goes to the button. If you already fixed the places of the bubbles in your mind, these are not at all a problem for you.. :P
Now let's come the coding part,
- (void) createRect:(CGRect)rect xPoint:(float)x yPoint:(float)y ofHeight:(float)height ofWidth:(float)width toPointX:(float)toX toPointY:(float)toY withString:(NSString *)helpString inDirection:(NSString *)direction
{
float distance = 5.0;
float widthOfLine = 5.0;
float arrowLength = 15.0;
//Get current context
CGContextRef context = UIGraphicsGetCurrentContext();
//Set width of border & colors of bubble
CGContextSetLineWidth(context, widthOfLine);
CGContextSetStrokeColorWithColor(context, [[UIColor darkGrayColor] CGColor]);
CGContextSetFillColorWithColor(context, [[UIColor colorWithRed:0 green:0 blue:0 alpha:0.9] CGColor]);
CGContextBeginPath(context);
CGContextMoveToPoint(context, x, y);
CGContextAddLineToPoint(context, x+width, y);
CGContextAddQuadCurveToPoint(context, x+width, y, x+width+distance, y+distance);
CGContextAddLineToPoint(context, x+width+distance, y+distance+height);
CGContextAddQuadCurveToPoint(context, x+width+distance, y+distance+height, x+width, y+distance+height+distance);
CGContextAddLineToPoint(context, x, y+distance+height+distance);
CGContextAddQuadCurveToPoint(context, x, y+distance+height+distance, x-distance, y+distance+height);
CGContextAddLineToPoint(context, x-distance, y+distance);
CGContextAddQuadCurveToPoint(context, x-distance, y+distance, x, y);
CGContextDrawPath(context, kCGPathFillStroke);
//Draw curvely arrow from bubble to button (but without arrow mark)
CGContextBeginPath(context);
CGContextSetLineWidth(context, 5.0);
CGContextSetStrokeColorWithColor(context, [[UIColor whiteColor] CGColor]);
CGPoint startPoint = CGPointMake(x+(width/2.0), y+distance+distance+height);
CGPoint endPoint = CGPointMake(toX, toY);
CGContextMoveToPoint(context, startPoint.x, startPoint.y+5.0);
if ([direction isEqualToString:#"left"])
{
CGContextAddCurveToPoint(context, startPoint.x, startPoint.y+5.0, endPoint.x, endPoint.y, toX-10, toY);
}
else
{
CGContextAddCurveToPoint(context, startPoint.x, startPoint.y+5.0, endPoint.x, endPoint.y, toX+10, toY);
}
CGContextStrokePath(context);
//Draw the arrow mark
CGContextBeginPath(context);
CGContextSetLineWidth(context, 5.0);
CGContextSetStrokeColorWithColor(context, [[UIColor whiteColor] CGColor]);
if ([direction isEqualToString:#"left"])
{
CGContextMoveToPoint(context, toX-10.0, toY-arrowLength);
CGContextAddLineToPoint(context, toX-10.0, toY);
CGContextAddLineToPoint(context, toX-10.0+arrowLength, toY);
}
else
{
CGContextMoveToPoint(context, toX+10.0, toY-arrowLength);
CGContextAddLineToPoint(context, toX+10.0, toY);
CGContextAddLineToPoint(context, toX+10.0-arrowLength, toY);
}
CGContextStrokePath(context);
.......
.......
}
You can call this method from the drawRect: method like this..
[self createRect:rect xPoint:30.0 yPoint:250.0 ofHeight:100.0 ofWidth:100.0 toPointX:48.0 toPointY:430.0 withString:#"xxxxxxx" inDirection:#"left"];
[self createRect:rect xPoint:160.0 yPoint:100.0 ofHeight:100.0 ofWidth:100.0 toPointX:260.0 toPointY:420.0 withString:#"yyyyyyy" inDirection:#"right"];
And the final image will be like this..
I skipped triangle shape arrow, because this arrow type gives a handwriting effect.
Thanks to #djromero and Ilker Baltaci for your valuable answers.
My next confusion is about Drawing Texts!!!!! :P

On iOS, why UIBezierPath drawing doesn't require a context?

On iOS, we can draw a line in drawRect using
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextBeginPath (context);
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, 100, 100);
CGContextStrokePath(context);
but we can also draw a rectangle if we remove the above code, and just use:
UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 100, 100)];
[path stroke];
Two related questions:
1) Why doesn't UIBezierPath need to get or use the current context?
2) What if I have two context: one for screen, and one is a bitmap context, then how to tell which context to draw to for UIBezierPath? I thought it might be UIGraphicsSetCurrentContext but it doesn't exist.
UIBezierPath does use a context. It uses the current UIKit graphics context. This is exactly the same thing that you're already getting with UIGraphicsGetCurrentContext().
If you want UIBezierPath to use a different context you can use UIGraphicsPushContext(), but you have to remember to use UIGraphicsPopContext() when you're done.
I thought it might be useful to mention that CGContextFillRect is ~8.5x faster than using a UIBezierPath from what I can tell (in case performance is a factor and assuming you don't need to use a UIBezierPath for more complex drawing).
I added some timing to Apple's HazardMap example (http://developer.apple.com/library/ios/#samplecode/HazardMap/Introduction/Intro.html) and the time in ms per rect is ~0.00064 ms/rect for the CGContextFillRect approach versus ~0.00543 ms/rect for the UIBezierPath approach, presumably b/c the latter requires more message passing overhead.
i.e. I'm comparing using
CGContextFillRect(ctx, boundaryCGRect);
versus using
UIBezierPath* path = [UIBezierPath bezierPathWithRect:boundaryCGRect];
[path fill];
in the inner loop in HazardMapView (plus the above-mentioned changes to push / pop the context that is passed to HazardMapView drawMapRect:zoomScale:inContext:).
ETA
On iOS, we can draw a line in drawRect using
I've highlighted the important part of this statement. Inside of drawRect:, a context has already been set up for you by UIKit, and any object-based drawing instructions go directly into that context. UIBezierPath is indeed using that context, it just doesn't need to be passed in explicitly.
In Cocoa Touch, there must always be a drawing context (in this case, the context will eventually be painted onto the screen). If you were not inside drawRect:, you'd have to create a context yourself.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextBeginPath (context);
CGContextMoveToPoint(context, 0, 0);
Notice that the first function call is GetCurrentContext(). When you're using CoreGraphics' functional drawing interface, you need to pass a context into each function, but you're not creating one here, you're just retrieving the one that already exists.
Graphics contexts are in a stack. If you want to draw into a context you've created, you push it onto the stack using UIGraphicsPushContext() (as Kevin already mentioned), then pop back to the previous one.

Drawing in drawRect is always called but doesn't always produce anything

I'm having a strange issue at the moment. I'm generating a drawing in a UIViewControllers UIView which calls drawRect:, goes through the entire code process without crashing but produces nothing. If I click on a UI object inside of the UIView the drawRect gets reloaded and my image appears.
The only good thing with this is that it happens every time at first load but it also happens some times later.
This usually works so am I missing something like a reload/set function?
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, rect);
CGContextSetRGBFillColor(context, 1, 1, 1, 1.0f);
CGContextFillRect(context, rect);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextSetLineWidth(context, 5.0);
CGContextMoveToPoint(context, 20, 20);
CGContextAddLineToPoint(context, 40, 40);
CGContextStrokePath(context);
Is your code calling -drawRect: directly? If so, stop that. Before calling -drawRect:, UIView sets up the drawing context so that all your -drawRect: override has to do is draw. If you try to call that method directly the drawing context won't be set up correctly and your drawing will end up in the wrong place, or nowhere at all. The drawing works correctly for you when you let the system manage drawing, in which case the context will be properly set before -drawRect: is called.
Sounds like your drawRect: code is not getting called when you expect it to be. Be sure you are calling setNeedsDisplay on your UIView as needed.

Core-Graphics Shadow Range?

In Photoshop, my designer used the "Range" setting to get the outer glow to "fill out" a little more. Here is a snapshot of the settings he used:
With the range in Photoshop set to 100%, here is the look:
That looks like my rendering on the iPhone using this code (assume the gradient fill and stroke around the circle are both working fine, we're only focusing on the glow):
CGContextAddPath(context, spectralImagePath);
CGContextSaveGState(context);
CGContextSetShadowWithColor(context, CGSizeMake(0.0, 0.0), 21.0, [[UIColor colorWithRed:65.0/255.0 green:79.0/255.0 blue:246.0/255.0 alpha:1.0] CGColor]);
CGContextSetBlendMode(context, kCGBlendModeScreen);
CGContextFillPath(context);
CGContextRestoreGState(context);
But, it needs to look like this (with range set to 50% in photoshop):
Notice how the shadow is a little more dense around the edges of the circle. Any ideas if Core Graphics contains a range-like property?
I don’t know of one. As an alternative, you might try just drawing the same shadowed path multiple times via repeated calls to CGContextFillPath.