UIView. How do I constrain scaling to one dimension only - iphone

I have an instance of UIScrollview containing an instance of UIView. The UIView is just a container for a horizonal array of UIImageView instances. - Zooming is provided by UIScrollView and UIScrollViewDelegate. I would like to constrain zooming to occur only along the horizontal axis with no vertical scalling at all. How to I do this?
Is there a way, for example, to subclass UIView and override the appropriate method to prevent vertical scaling? I like this approach but I am unclear on which method to override and what that overridden method should actually do.
Cheers,
Doug

Similar to what I describe in this answer, you can create a UIView subclass and override the -setTransform: accessor method to adjust the transform that the UIScrollView will try to apply to your UIView. Set this UIView to host your content subviews and make it the subview of the UIScrollView.
Within your overridden -setTransform:, you'll need to take in the transform that the UIScrollView would like to apply and adjust it so that the scaling only takes effect in one direction. From the documentation on how CGAffineTransform matrices are constructed, I believe the following implementation should constrain your scaling to be just along the horizontal direction:
- (void)setTransform:(CGAffineTransform)newValue;
{
CGAffineTransform constrainedTransform = CGAffineTransformIdentity;
constrainedTransform.a = newValue.a;
[super setTransform:constrainedTransform];
}

Using OS 3.0, you can tell the zoom to zoom to a rect in the scrollview. I have this in my logic that detects taps.
CGRect zoomRect = [self zoomRectForScale:newScale withCenter:CGPointMake(tapPoint.x, tapPoint.y) inScrollView:scrollView];
[scrollView zoomToRect:zoomRect animated:YES];
The for the other part, you will have to stretch your image views by the ratio that the new frame has against the original, and center it in the same center point. You can do this in an animation timed the same as the zoom animation so that it looks right, but I think this will be the only way to do it.

In scrollViewDidZoom:, adjust your content view's variables based on zoomScale, reset zoomScale to 1.0, then do setNeedsDisplay on the content view. Handle the actual zoom (in whatever direction you want) in your content view's drawRect:.
The Ugly Details:
While the zoom is in progress, the UIScollView changes contentOffset and contentScale, so save those prior values in scrollViewWillBeginZooming: and in scrollViewDidZoom: so you can compute a new contentOffset yourself according to the zoom.
Since changing zoomScale will immediately fire another scrollViewDidZoom:, you must set a BOOL before (and clear after) resetting the zoomScale. Test the BOOL at the start of scrollViewDidZoom: and return if true.
You may need to inhibit scrollViewDidScroll: while the zoom is in progress (test a BOOL; set it in scrollViewWillBeginZooming: and clear it in scrollViewDidEndZooming:) so your own contentOffsets are used while the zoom is in progress.

Related

convertRect fromView not returning correct frame after rotation

I have a problem I've run into with the UIView method convertRect: fromView: method. Here is the situation:
I have an overwritten the UIView class to create a view that rotates with the user's movement(very similar to the TaskRabbit spinner). To create the rotation, over I added an additional view to my subclassed view, and I rotated that view. The rotated view contains additional subviews that obviously rotate with the rotated subview. The problem is, after the subview has been rotated, I need to find where those additional subviews are, with respect to the original overritten view - not the rotated view. To do this, in my UIView class, I have the following:
[self convertRect:currentView.frame fromView:rotationView];
However, when I print out the frame of the converted rect, the coordinates are not accurate. Has anyone run into this issue where the convertRect: fromView: isn't accurate after the view is rotated?
Edit
Specifically, about the points being not accurate, I can't even see the relationship between what is should be and what it is-ie off by an specific angle, x/y flipped etc. For example, the point that should be (25, 195) is returned at (325.25, 273.16)
I'm assuming that you are rotating your views by applying a transform to them (either a CGAffineTransform to the view or a CATransform3D to the layer). This is what is causing the problem with your frame. The documentation for UIView frame says:
Warning If the transform property is not the identity transform, the value of this property is undefined and therefore should be ignored.
As you've already seen, the value of the frame is undefined. You can still use the center and bounds properties though.

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;
}

Efficient method to find subviews outside of frame of view

I have an array of views that are also subviews of a base view. I want to efficiently remove all views that are not inside the frame of the base view (i.e. not visible).
I'm looking for suggestions to find the most efficient method besides of computing the intersection of all frames with the base view frame.
If you want to remove your subviews when they are not inside the base view's frame, you will need to calculate their frames intersections with the base view. Alternatively, you could use bool CGRectContainsRect ( CGRect rect1, CGRect rect2 ); instead of fully calculating the intersection.
If you are trying to do this to optimize subview drawing, you can think of using the UIView'scliptobounds property, instead of removing the subviews:
clipsToBounds
A Boolean value that determines whether subviews are confined to the bounds of the receiver.
#property(nonatomic) BOOL clipsToBounds
Discussion
Setting this value to YES causes subviews to be clipped to the bounds of the receiver. If set to NO, subviews whose frames extend beyond the visible bounds of the receiver are not clipped. The default value is NO.

iOS - Animating text size change in UILabel or UITextView?

In an application showing chunks of text, I'm having the font size increase when the device is turned to a landscape orientation. I don't like how it does the whole animation and then suddenly jumps to the new size, so I'd like to animate the size change over the course of the rotation.
I read somewhere that throwing this change in a UIView animation block doesn't work because the font property is not animatable, so what are my options for doing this?
For my specific implementation I'm not simply scaling the UILabel/UITextView as-is; The bounds of the box is increasing more (proportionally) than the font-size, so there will be re-flow in the text. That's fine by me.
Edit: I would be fine with simply scaling the UITextView.
Also, I was considering "animating" it manually: I have a method that lays out my views and adjusts for font size. If I knew when the rotation was about to start, and the duration of the animation, I could time it so it renders an intermediate font size or two in the middle of the animation. Any help with getting those would be appreciated.
One option is to fade the old text out, change the font size, and fade it back in. The font property may not be animatable, but alpha is. Since alpha is a property of UIView, you can treat all your text-bearing views the same way: UILabel, UITextView, etc. It looks good, too.
If I knew when the rotation was about
to start, and the duration of the
animation...
Funny you should mention that. Just before the animation starts, your view controller will receive a willAnimateRotationToInterfaceOrientation:duration: message that gives you the exact information you need.
A way to proceed could be to:
Create a CAKeyframeAnimation
Define the scaling and rotation you want to achieve during that animation using a set of CATransform3D objects
Add these transforms to your keyframed animation
Send the addAnimation message to your label layer object: [[label layer] addAnimation];
Here would be a code sample assuming yourLabel is the UILabel you want to scale and rotate:
CAKeyframeAnimation *scale = [CAKeyframeAnimation animationWithKeyPath:#"transform"];
CATransform3D scaleUp = CATransform3DMakeScale(1.5, 1.5, 1); // Scale in x and y
CATransform3D rotationScaled = CATransform3DRotate (scaleUp, 90, 0, 0, 1); // Rotate the scaled font
[scale setValues:[NSArray arrayWithObjects:
[NSValue valueWithCATransform3D:CATransform3DIdentity],
[NSValue valueWithCATransform3D:rotationScaled],
nil]];
// set the duration
[scale setDuration: 1.0];
// animate your label layer
[[yourLabel layer] addAnimation:scale forKey:#"scaleText"];
This is typically how a text bouncing around would be animated for instance.
You could start this when the device starts rotating and retrieve the animation when it's done rotating so you can update your label with the proper scale/position.
You will need tuning to find the proper timing and rotation.
Change the font size when didAnimateFirstHalfOfRotationToInterfaceOrientation: is called.
That way the user won't see the change once the rotation completed. It would be pretty hard to see the font size change then, as the rotation is happening!

What happens to the view.frame.size attribute after a CGAffineTransform (Rotate)?

I have a UIImageView that can be resized by pinching in and out (Example: view.frame.size.width+10). The image of the Image View can also be rotated (CGAffineTransformMakeRotate). Okay, here is the problem: When I resize the UIImageView AFTER having had applied a Rotate Transform the view resizes abnormally (inversly (shrink when it should grow, vice-versa) or at enormous resize unit increments). How can I resize my UIImageView in a consistent manner whether or not a CGAffineTransform is applied?
There's a warning in the documentation for UIView that says, for the frame property:
Warning: If the `transform` property is not the identity transform, the value of this property is undefined and therefore should be ignored.
Use the bounds and center properties instead; they remain viable after a transform is applied.