CALayer is not drawing its content while CABasicAnimation is used - iphone

I have an application with a custom CALayer subclass. In this layer subclass i have overwritten the - (void) drawInContext:(CGContextRef)ctx method. This works fine and all my custom content is drawn.
Now I wanted to add a custom property which gets animated when it's content is changed. And I need to redraw while the animation is running. I added the property like given in the answer to the following question: Animating a custom property of CALayer subclass
And I also added an CABasicAnimation instance for this property to my layer:
CABasicAnimation* theAnimation=[CABasicAnimation animationWithKeyPath:#"moveContentToLeft"];
theAnimation.duration=1.0;
theAnimation.fromValue=[NSNumber numberWithFloat:0.0];
theAnimation.toValue=[NSNumber numberWithFloat:10.0];
[area addAnimation:theAnimation forKey:#"moveContentToLeft"];
In my draw method I have a NSLog statement in which I output the value of my property I'm animating.
My problem is that as soon as the animation starts all the content of the layer subclass is cleared. The NSLog outputs the values of my property that gets interpolated (so the drawInContext method) is called. But somehow the things it draws are not visible during the animation. At the end of the animation the original content gets visible again.
At the moment the animated property is not yet used while drawing the layer so I would expect that the normal content would get drawn again and I get the output of the NSLog with the interpolated values.
My layer is a child of another layer (inside a UIView). I tried to redraw the super layer at the end of the drawing method (with calling _parent setNeedsDisplay [parent is a ivar to the parent view]). This did not help. And I also have the feeling that this is not a good idea to do so.
I hope somebody can help me with this problem.
Update
Thanks to the example project from Matt Long I could see that my problem lies inside the drawing method. I extended his project so it shows the same problem. I think it is simpler to show than the original code ;)
- (void)drawInContext:(CGContextRef)ctx
{
NSLog(#"Getting called: Bob: %i", [self bob]);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(50 + [self bob], 50, 100, 100));
CGContextAddPath(ctx, path);
CGContextSetStrokeColorWithColor(ctx, [UIColor redColor].CGColor);
CGContextSetLineWidth(ctx, 1.0);
CGContextStrokePath(ctx);
CGPathRelease(path);
[_test testInContext:ctx]; // here is the problem
}
The ivar _test is a custom class which contains some drawing code (at the moment it draws a green box). The problem now is that this green box will not be drawn while the animation runs. As soon as the animation is ended the green box is visible again. The extended example project: http://dl.dropbox.com/u/5426092/ArbitraryPropertyAnimationNew.zip

It's hard to say what's going wrong without seeing more code. I have an example app that animates a custom property and the position of a layer at the same time. You can take a look at my source and see what's different.

Related

Drawing a straight line between two points by dragging on IOS

I have two square images in my UIVIew. Once I drag my finger from one image to another image I want to draw a straight line between them.
I have handled touchesMoved method to check when my touchLocation reaches the frame of either of the images. So I have handled the logic part of when to start drawing and between which two points.
I just cant figure out how to do that using (void)drawRect:(CGRect)rect. For one thing, I addded an NSlog in my drawRect and I wrote code to draw a line between two lines, even that's not happening.
I checked this question too, but I want to continue to drag and draw lines between multiple points.
- (void)drawRect:(CGRect)rect
{
NSLog(#"Draw Rect Entered");
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetStrokeColorWithColor(context, [[UIColor blackColor]CGColor]);
CGContextSetLineWidth(context, 1.0);
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, 20, 20);
CGContextStrokePath(context);
}
In order for the view to update you need to call -setNeedsDisplay or -setNeedsDisplayInRect: on the view that needs to be redrawn. You should do this in the touch handler once you have determined you need to draw the line. This will trigger the -drawRect: method on the view- you don't call -drawRect directly. For more information, read the UIView docs. I don't know whether you want your line to exist permanently once created- if there's a possibility it might be deleted, I'd add an if statement to -drawRect: controlled by a boolean determining whether to draw the line or not. Then you can easily switch it off if necessary.
Based on your comments below, I'd create an ivar array in which to store the points for the currently traced line and then loop over them in -drawRect:, using the Core graphics functions to draw the line a segment at a time. That way the new segment and all previous segments will be drawn with each redraw. Since CGPoint isn't an obj-c object, you'll either have to create a wrapper class or use obj-C++ and std::vector. You could also use a fixed size C-Array, (you mention you have precisely 10 points)- in that case you'd have to preset the unused coordinates to some arbitrary value defined as invalid (e.g. -500,-500) and add logic to not draw line segments if those values are encountered.
Minor point- I wouldn't hardcode the line coordinates - instead you could derive them from the images' frame property. That way your code will be more readable and won't break if you change the images or resize them.
There are two issues I have run into that could cause this problem:
1) Make sure you are calling setNeedsDisplay on the main thread
2) If you are working with multiple views make sure you are calling setNeedsDisplay against the correct one.
It is easy to work with one view and forget to call setNeedsDisplay against the parent view.

How could I trick [CALayer renderInContext: ] to render only a section of the layer?

I'm well aware that there's no nice way to render a small part of a UIView to an image, besides rendering the whole view and cropping. (VERY expensive on something like an iPad 3, where the resulting image is huge). See here for a description of the renderInContext method (there's no alternatives).
The part of the view that I want to render can't be predetermined, meaning I can't set up the view hierarchy for the small section to be it's own UIView (and therefore CALayer).
My Idea...
I had an idea, but I need some direction if I'm going to succeed. What if I create a category on UIView (or CALayer) that adds a method along the lines of:
[UIView renderSubframe:(CGFrame)frame];
How? Well, I'm thinking that if a dummy view the size of the sub frame was created, then the view could be shifted temporarily onto this. Then the dummy view's layer could call renderInContext:, resulting in an efficient and fast way of getting views.
So...
I'm really not that up to speed with CALayer/Quartz core stuff... Will this have any chance of working? If not, what's another way I could achieve the same thing - what's the most efficient way I could achieve the same result (or has anyone else already faced this problem and come up with a different solution)?
Here's the category I ended up writing. Not as hard as I first thought, thanks to a handy CGAffineTransform.
#import "UIView+RenderSubframe.h"
#import <QuartzCore/QuartzCore.h>
#implementation UIView (RenderSubframe)
- (UIImage *) renderWithBounds:(CGRect)frame {
CGSize imageSize = frame.size;
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextConcatCTM(c, CGAffineTransformMakeTranslation(-frame.origin.x, -frame.origin.y));
[self.layer renderInContext:c];
UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return screenshot;
}
#end
A couple of different ways you might do this:
specify a CGContextClipToRect for your context before calling renderInContext;
use:
setNeedsDisplayInRect:
Marks the region within the specified rectangle as needing to be updated.
- (void)setNeedsDisplayInRect:(CGRect)theRect
This would make the rendering happen only in the specified rect. I am not sure though whether this would work as per your requirement.
I think that the first option should work seamlessly.

Loading UIView transform & center from settings gives different position

I'm using pan, pinch, and rotate UIGestureRecognizers to allow the user to put certain UI elements exactly where they want them. Using the code from here http://www.raywenderlich.com/6567/uigesturerecognizer-tutorial-in-ios-5-pinches-pans-and-more (or similar code from here http://mobile.tutsplus.com/tutorials/iphone/uigesturerecognizer/) both give me what I need for the user to place these UI elements as they desire.
When the user exits "UI layout" mode, I save the UIView's transform and center like so:
NSString *transformString = NSStringFromCGAffineTransform(self.transform);
[[NSUserDefaults standardUserDefaults] setObject:transformString forKey:#"UItransform", suffix]];
NSString *centerString = NSStringFromCGPoint(self.center);
[[NSUserDefaults standardUserDefaults] setObject:centerString forKey:#"UIcenter"];
When I reload the app, I read the UIView's transform and center like so:
NSString *centerString = [[NSUserDefaults standardUserDefaults] objectForKey:#"UIcenter"];
if( centerString != nil )
self.center = CGPointFromString(centerString);
NSString *transformString = [[NSUserDefaults standardUserDefaults] objectForKey:#"UItransform"];
if( transformString != nil )
self.transform = CGAffineTransformFromString(transformString);
And the UIView ends up rotated and scaled correctly, but in the wrong place. Further, upon entering "UI layout" mode again, I can't always grab the view with the various gestures (as though the view as displayed is not the view as understood by the gesture recognizer?)
I also have a reset button that sets the UIView's transform to the identity and its center to whatever it is when it loads from the NIB. But after loading the altered UIView center and transform, even the reset doesn't work. The UIView's position is wrong.
My first thought was that since those gesture code examples alter center, that rotations must be happening around different centers (assuming some unpredictable sequence of moves, rotations, and scales). As I don't want to save the entire sequence of edits (though that might be handy if I want to have some undo feature in the layout mode), I altered the UIPanGestureRecognizer handler to use the transform to move it. Once I got that working, I figured just saving the transform would get me the current location and orientation, regardless of in what order things happened. But no such luck. I still get a wacky position this way.
So I'm at a loss. If a UIView has been moved and rotated to a new position, how can I save that location and orientation in a way that I can load it later and get the UIView back to where it should be?
Apologies in advance if I didn't tag this right or didn't lay it out correctly or committed some other stackoverflow sin. It's the first time I've posted here.
EDIT
I'm trying the two suggestions so far. I think they're effectively the same thing (one suggests saving the frame and the other suggests saving the origin, which I think is the frame.origin).
So now the save/load from prefs code includes the following.
Save:
NSString *originString = NSStringFromCGPoint(self.frame.origin);
[[NSUserDefaults standardUserDefaults] setObject:originString forKey:#"UIorigin"];
Load (before loading the transform):
NSString *originString = [[NSUserDefaults standardUserDefaults] objectForKey:#"UIorigin"];
if( originString ) {
CGPoint origin = CGPointFromString(originString);
self.frame = CGRectMake(origin.x, origin.y, self.frame.size.width, self.frame.size.height);
}
I get the same (or similar - it's hard to tell) result. In fact, I added a button to just reload the prefs, and once the view is rotated, that "reload" button will move the UIView by some offset repeatedly (as though the frame or transform are relative to itself - which I'm sure is a clue, but I'm not sure what it's pointing to).
EDIT #2
This makes me wonder about depending on the view's frame. From Apple http://developer.apple.com/library/ios/#documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/WindowsandViews/WindowsandViews.html#//apple_ref/doc/uid/TP40009503-CH2-SW6 (emphasis mine):
The value in the center property is always valid, even if scaling or rotation factors have been added to the view’s transform. The same is not true for the value in the frame property, which is considered invalid if the view’s transform is not equal to the identity transform.
EDIT #3
Okay, so when I'm loading the prefs in, everything looks fine. The UI panel's bounds rect is {{0, 0}, {506, 254}}. At the end of my VC's viewDidLoad method, all still seems okay. But by the time things actually are displayed, bounds is something else. For example: {{0, 0}, {488.321, 435.981}} (which looks like how big it is within its superview once rotated and scaled). If I reset bounds to what it's supposed to be, it moves back into place.
It's easy enough to reset the bounds to what they're supposed to be programatically, but I'm actually not sure when to do it! I would've thought to do it at the end of viewDidLoad, but bounds is still correct at that point.
EDIT #4
I tried capturing self.bounds in initWithCoder (as it's coming from a NIB), and then in layoutSubviews, resetting self.bounds to that captured CGRect. And that works.
But it seems horribly hacky and fraught with peril. This can't really be the right way to do this. (Can it?) skram's answer below seems so straightforward, but doesn't work for me when the app reloads.
You would save the frame property as well. You can use NSStringFromCGRect() and CGRectFromString().
When loading, set the frame then apply your transform. This is how I do it in one of my apps.
Hope this helps.
UPDATE: In my case, I have Draggable UIViews that rotation and resizing can be applied to. I use NSCoding to save and load my objects, example below.
//encoding
....
[coder encodeCGRect:self.frame forKey:#"rect"];
// you can save with NSStringFromCGRect(self.frame);
[coder encodeObject:NSStringFromCGAffineTransform(self.transform) forKey:#"savedTransform"];
//init-coder
CGRect frame = [coder decodeCGRectForKey:#"rect"];
// you can use frame = CGRectFromString(/*load string*/);
[self setFrame:frame];
self.transform = CGAffineTransformFromString([coder decodeObjectForKey:#"savedTransform"]);
What this does is save my frame and transform, and load them when needed. The same method can be applied with NSStringFromCGRect() and CGRectFromString().
UPDATE 2: In your case. You would do something like this..
[self setFrame:CGRectFromString([[NSUserDefaults standardUserDefaults] valueForKey:#"UIFrame"])];
self.transform = CGAffineTransformFromString([[NSUserDefaults standardUserDefaults] valueForKey:#"transform"]);
Assuming you're saving to NSUserDefaults with UIFrame, and transform keys.
I am having trouble reproducing your issue. I have used the following code, which does the following:
Adds a view
Moves it by changing the centre
Scales it with a transform
Rotates it with another transform, concatenated onto the first
Saves the transform and centre to strings
Adds another view and applies the centre and transform from the string
This results in two views in exactly the same place and position:
- (void)viewDidLoad
{
[super viewDidLoad];
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
view1.layer.borderWidth = 5.0;
view1.layer.borderColor = [UIColor blackColor].CGColor;
[self.view addSubview:view1];
view1.center = CGPointMake(150,150);
view1.transform = CGAffineTransformMakeScale(1.3, 1.3);
view1.transform = CGAffineTransformRotate(view1.transform, 0.5);
NSString *savedCentre = NSStringFromCGPoint(view1.center);
NSString *savedTransform = NSStringFromCGAffineTransform(view1.transform);
UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
view2.layer.borderWidth = 2.0;
view2.layer.borderColor = [UIColor greenColor].CGColor;
[self.view addSubview:view2];
view2.center = CGPointFromString(savedCentre);
view2.transform = CGAffineTransformFromString(savedTransform);
}
Giving:
This ties up with what I would expect from the documentation, in that all transforms happen around the centre point and so that is never affected. The only way I can imagine that you're not able to restore items to their previous state is if somehow the superview was different, either with its own transform or a different frame, or a different view altogether. But I can't tell that from your question.
In summary, the original code in your question ought to be working, so there is something else going on! Hopefully this answer will help you narrow it down.
You should the also save the UIView's location,
CGPoint position = CGPointMake(self.view.origin.x, self.view.origin.y)
NSString _position = NSStringFromCGPoint(position);
// Do the saving
I'm not sure of everything that's going on, but here are some ideas that may help.
1- skram's solution seems plausible, but it's the bounds you want to save, not the frame. (Note that, if there's been no rotation, the center and bounds define the frame. So, setting the two is the same as setting the frame.)
From, the View Programming Guide for IOS you linked to:
Important If a view’s transform property is not the identity
transform, the value of that view’s frame property is undefined and
must be ignored. When applying transforms to a view, you must use the
view’s bounds and center properties to get the size and position of
the view. The frame rectangles of any subviews are still valid because
they are relative to the view’s bounds.
2- Another idea. When you reload the app, you could try the following:
First, set the view's transform to the identity transform.
Then, set the view's bounds and center to the saved values.
Finally, set the view's transform to the saved transform.
Depending on where your app is restarting, it may be starting back up with some of the old geometry. I really don't think this will change anything, but it's easy enough to try.
Update: After some testing, it really does seem like this wouldn't have any effect. Changing the transform does not seem to change the bounds or center (although it does change the frame.)
3- Lastly, you may save some trouble by rewriting the pinch gesture recognizer to operate on the bounds rather than the transform. (Again, use bounds, not frame, because an earlier rotation could have rendered the frame invalid.) In this way, the transform is used only for rotations, which, I think, cannot be done any other way without redrawing.
From the same guide, Apple's recommendation is:
You typically modify the transform property of a view when you want to
implement animations. For example, you could use this property to
create an animation of your view rotating around its center point. You
would not use this property to make permanent changes to your view,
such as modifying its position or size a view within its superview’s
coordinate space. For that type of change, you should modify the frame
rectangle of your view instead.
Thanks to all who contributed answers! The sum of them all led me to the following:
The trouble seems to have been that the bounds CGRect was being reset after loading the transform from preferences at startup, but not when updating the preferences while modifying in real time.
I think there are two solutions. One would be to first load the preferences from layoutSubviews instead of from viewDidLoad. Nothing seems to happen to bounds after layoutSubviews is called.
For other reasons in my app, however, it's more convenient to load the preferences from the view controller's viewDidLoad. So the solution I'm using is this:
// UserTransformableView.h
#interface UserTransformableView : UIView {
CGRect defaultBounds;
}
// UserTransformableView.m
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if( self ) {
defaultBounds = self.bounds;
}
return self;
}
- (void)layoutSubviews {
self.bounds = defaultBounds;
}

How to keep the previous drawing when using Quartz on the iPhone?

I want to draw a simple line on the iPhone by touching and dragging across the screen. I managed to do that by subclassing UIView and change the default drawRect: method. At the same time in my viewcontroller I detect the touch event and call the [myView setNeedsDisplay] when necessary. The problem is that when I try to draw the second line the previous line disappears. Is there a way to keep the previous line on the screen?
Any input will be very much appreciated.
The usual method is to use CGBitmapContextCreate(). Create it in -init/-init-WithFrame:/etc and call CGContextRelease() in -dealloc. I'm not sure how you handle the 2x scale of the "retina display" with CGBitmapContextCreate().
(UIGraphicsBeginImageContext() is easier, but it might not be safe to do UIGraphicsBeginImageContext(); myContext = CFRetain(UIGraphicsGetCurrentContext()); UIGraphicsEndImageContext();.)
Then do something like
#import <QuartzCore/CALayer.h>
-(void)displayLayer:(CALayer*)layer
{
UIGraphicsPushContext(mycontext);
... Update the bitmap context by drawing a line...
UIGraphicsPopContext();
CGImageRef cgImage = CGBitmapContextCreateImage(mycontext);
layer.contents = (id)cgImage;
CFRelease(cgImage);
}
I've used -displayLayer: (a CALayer delegate function; a UIView is its layer's delegate) instead of -drawRect: for efficiency: if you use -drawRect:, CALayer creates a second context (and thus a second copy of the bitmap).
Alternatively, you might have luck with CGLayer. I've never seen a reason to use it instead of a bitmap context; it might be more efficient in some cases.
Alternatively, you might get away with setting self.clearsContextBeforeDrawing = NO, but this is very likely to break. UIKit (or, more accurately, CoreAnimation) expects you to draw the whole view contained in the clip rect (that's the "rect" argument of -drawRect:; it's not guaranteed to be the bounds). If your view goes offscreen, CoreAnimation might decide that it wants the memory back. Or CoreAnimation might only draw the part of the view that's on-screen. Or CoreAnimation might do double-buffered drawing, causing your view to appear to flip between two states.
If you use drawRect: to draw, then you need to draw the whole area. So you need to store not only the data for the latest part but everything.
As an alternative, you might draw directly into a bitmap, or generate dynamically subviews for your lines (makes only sense for very limited drawing (i.e. some few vector-based stuff).

How do I draw a point inside of an instance of UIImageView?

How do I use Core Graphics to draw inside of a instantiated UIImageView (No class files to override drawrect with -- just a reference to the instance)? I want to draw a simple point of fixed width (say, 10 pixels diameter) and of a certain color.
How do I use Core Graphics to … draw a simple point of fixed width (say, 10 pixels diameter) and of a certain color[?]
Set the fill color.
Move to the point.
Plot an arc, centered at the point, with the desired radius, giving a start angle of 0 and an end angle of 2 * M_PI.
Close the path.
Fill.
… draw inside of a instantiated UIImageView (No class files to override drawrect with -- just a reference to the instance)
I know that on the Mac, that's really not a good idea, as an NSView may redraw at any time if anything has set it as needing display (or told it directly to display), and would then clobber anything you'd drawn over it. No idea about the iPhone, but I do notice that UIView doesn't have methods like NSView's lockFocus and unlockFocus.
There's a more architectural reason not to do this: Drawing is the exclusive domain of views, and you're proposing to break that exclusivity and sprinkle some drawing code in (I'm assuming) a controller. Scattering code for a purpose in an object that doesn't have that purpose is a path to messy, unnavigable code.
Better to make a subview for each point and add those as subviews of the image view, or subclass UIImageView, give your instance of that subclass an array of the points to draw, and have the subclass's drawRect: call up to super before drawing its points.
The above solution, then, goes in drawRect:.
You can also just add a Core Animation layer to the view. Set the corner radius to half the size of the point you want (assuming a square) and it will render as a circle. Something like:
CALayer *layer = [CALayer layer];
[layer setBounds:CGRectMake(0.0f, 0.0f, 10.0f, 1.0f)];
[layer setCornerRadius:5.0f];
[layer setMasksToBounds:YES];
[layer setBackgroundColor:[[UIColor redColor] CGColor]];
// Center the layer in the view.
[layer setPosition:CGPointMake([view bounds].size.width/2,
[view bounds].size.height/2)];
// Add the layer to your view
[[view layer] addSublayer:layer];
Not Core Graphics exactly, but it's easy to implement.
Best Regards,