UIScrollView zoom to rect - ios

I'm trying to zoom inside a UIScrollView by specifying a rect which is within scrollview's coordinates. However it's not working as expected. and I think it's because of zoom scale or maybe I'm missing a transformation. The scroll view I'm trying to zoom is from the Apple's example PhotoScroller -- ImageScrollView. Also I copied the code to generate a frame to zoom from Apple's example as well:
- (CGRect)zoomRectForScrollView:(UIScrollView *)scrollView withScale:(float)scale withCenter:(CGPoint)center {
CGRect zoomRect;
// The zoom rect is in the content view's coordinates.
// At a zoom scale of 1.0, it would be the size of the
// imageScrollView's bounds.
// As the zoom scale decreases, so more content is visible,
// the size of the rect grows.
zoomRect.size.height = scrollView.frame.size.height / scale;
zoomRect.size.width = scrollView.frame.size.width / scale;
// choose an origin so as to get the right center.
zoomRect.origin.x = center.x - (zoomRect.size.width / 2.0);
zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0);
return zoomRect;
}
Now the code to actually zoom is the following:
CGPoint scrollRectCenter = CGPointMake(rect.origin.x + (rect.size.width /2) ,
rect.origin.y + (rect.size.height / 2));
CGFloat newZoomScale = self.imageScrollView.zoomScale * 1.3f;
newZoomScale = MIN(newZoomScale, self.imageScrollView.maximumZoomScale);
CGRect zoomToRect = [self zoomRectForScrollView:self.imageScrollView withScale:newZoomScale withCenter:scrollRectCenter];
[self.imageScrollView zoomToRect:zoomToRect animated:YES];
How can I zoom to a rect taking in consideration the zoomed imageView zoomscale, so that it fit's correctly?
What I'm trying to achieve is the effect of the photos app, in which the crop grid is moved and the scrollview zooms to that rect.
Does anybody know a link or code example to achieve a similar effect to the photos app? Thanks a lot.

Let me guess...you have implemented - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale delegate method.
Your problem occurs because when this method is called the scrollview's zoom scale is reseted to 1. I don't know why, don't ask me.
You can fix it in 2 ways :
you save the scale into a variable and in - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale you set your variable to the appropriate scale and do the calculations with your scale.
You don't implement the bloody method, unless you have multiple views in your scrollview and each can zoom individually it doesn't worth it (after all you can access the zoom scale with scrollview.zoomScale)
If you don't implement the method disregard this answer :)

Related

How does anchorPoint influence center in a UIView?

I'm working on an app that lets the user resize and rotate a photo using UIGestureRecognizers. I have this code which adjusts the anchorPoint based on where the user is applying touches (to make it look like they're scaling the image at the point where their fingers actually are):
- (void)adjustAnchorPointForGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
{
UIView *gestureRecognizerView = gestureRecognizer.view;
CGPoint locationInView = [gestureRecognizer locationInView:gestureRecognizerView];
CGPoint locationInSuperview = [gestureRecognizer locationInView:gestureRecognizerView.superview];
gestureRecognizerView.layer.anchorPoint = CGPointMake(locationInView.x / gestureRecognizerView.bounds.size.width, locationInView.y / gestureRecognizerView.bounds.size.height);
gestureRecognizerView.center = locationInSuperview;
}
Later on, I'm simply wanting to calculate the origin based on the center and bounds with this code:
CGRect transformedBounds = CGRectApplyAffineTransform(view.bounds, view.transform);
CGPoint origin = CGPointMake(view.center.x - (transformedBounds.size.width * view.layer.anchorPoint.x), view.center.y - (transformedBounds.size.height * view.layer.anchorPoint.y));
And it's coming out incorrectly (I'm comparing against the frame value which ironically is supposed to be invalidated but actually does have the correct value).
So all in all I'm wondering, what am I not taking into account here? How is the anchorPoint influencing the center in a way I'm not able to determine?
I think the problem is that the origin you are calculating is not really an origin, but rather an offset of the origin of your transformedBounds rect.
I haven't fully tested it, but if you do something like this you should get the correct frame:
CGRect transformedBounds =
CGRectApplyAffineTransform(view.bounds, view.transform);
CGSize originOffset = CGSizeMake(
view.center.x - (transformedBounds.size.width * view.layer.anchorPoint.x),
view.center.y -
(transformedBounds.size.height * view.layer.anchorPoint.y));
transformedBounds.origin.x += originOffset.width;
transformedBounds.origin.y += originOffset.height;

Setting UIImage transform affects UIScrollView

My aim is to create an UIImage that scales automatically as I scroll in an UIScrollView. This works just fine but as soon as the scale of my image is set to something like .6 you aren't able to scroll in the UIScrollView anymore (even if you reset the scaling to 1 or 0.5 or/and reassign the content size of the scrollview). This is very strange because setting the scaling to 1, .75, .5 or .25 doesn't affect the scrollview (i. e. it works as it should). I'm using transform instead of setting the frame size because I want the image to be centered by the AutoLayout. Is there a better way of scaling an image without touching frame? And why does setting the scaling of an image affect a scrollview at all?
This is the code I'm using for resizing the image:
- (void)scrollViewDidScroll:(UIScrollView *)sender {
CGFloat pageWidth = sideScroller.frame.size.width;
CGFloat scrollOffset = sideScroller.contentOffset.x;
float fractionalPage = scrollOffset / pageWidth;
NSInteger page = lround(fractionalPage);
[pageControl setCurrentPage:page];
if (scrollOffset > pageWidth)
scrollOffset = (pageWidth * 2) - scrollOffset;
float logoSize = 1 - ((scrollOffset / pageWidth) / 2);
logo.transform = CGAffineTransformMakeScale(logoSize, logoSize);
}
Just a guess but the content size of the content inside of the scroll view isn't changing because of the transform. Try scaling by frame instead.

UIButton position while UIImage zoom on UIScrollView

I have a scenario where I need to implement an Offline Map concept for which I am using the image of map on a UIScrollView that zooms on PinchGesture, which works fine.
Problem
I have a UIButton on map. While zooming, the button does not track its position with respect to UIImageView which is being scaled.I am able to reframe the button without affecting its size. But the position is wrong.
TLDR,
I need to reproduce the mapView with annotation kinda concept on UIScrollView with UIImage on it. Can any one help?
Thanks in advance :)
I have found the answer for this. I initially stored the button value in a CGRect initialButtonFrame. Then I updated the button frame (only origins, not the size of the button size as I wanted the button not to zoom like the image ie; I button should not zoom) using the scrollview delegate
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
{
[self manageImageOnScrollView];//here i managed the image's coordinates and zoom
[self manageButtonCoordinatesWithRespectToImageWithScale:scale];
}
-(void)manageButtonCoordinatesWithRespectToImageWithScale:(float)scaleFactor
{
//initialButtonFrame is frame of button
self.button.frame = CGRectMake((initialButtonFrame.origin.x * scaleFactor),
(initialButtonFrame.origin.y * scaleFactor),
initialButtonFrame.size.width,
initialButtonFrame.size.height);
[self.scrollView addSubview:self.button];// I removed the button from superview while zooming and later added with updated button coordinates which I got here
}
If you know your current offset and zoom of your map, you should be able to compute the position of your button:
//Assuming your map image has its origin at 0, 0
CGPoint mapOffsetX, mapOffsetY; // these would come from your map as you calculated it.
CGPoint mapZoomFactor; // 1.0 means not zoomed, 3.0 means zooming in 3x, etc
CGPoint buttonAnchorPosition; //the position of your button on your map at 1.0 zoom
CGFloat buttonX = buttonAnchorPosition.x * mapZoomFactor + mapOffsetX;
CGFloat buttonY = buttonAnchorPosition.y * mapZoomFactor + mapOffsetY;
CGPoint buttonPosition = CGPointMake(buttonX, buttonY);
button.position = buttonPosition;
Try that, good luck

Overriding "bitmap scaling" effect of UIScrollView zooming

In my iPad app, Universal Combat Log (new-layout branch), I have a UIView subclass (UCLLineChartView) which contains a UIScrollView and the scrollview in turn contains another UIView subclass (ChartView). ChartView has multiple sub-layers, one for each line of data that has been added to the chart. UCLLineChartView draws the axes and markers. The contents of these views/layers are entirely custom drawn, no stock views are used (e.g. UIImageView).
I'm having a problem with zooming -- it's scaling the ChartView like an image, which makes the drawn line all blurred and stretched. I want the line to stay sharp, preferably even while the user is in the act of zooming, but after 3 days of hacking at this, I cannot get it to work.
If I override setTransform on the ChartView to grab the scale factor from the transform but don't call [super setTransform], then the scrollview's zoomScale stays at 1. I tried keeping the given transform and overriding the transform method to return it. I tried replicating the effects of setTransform by changing the ChartView's center and bounds but I wasn't able to get the behaviour quite right and it still didn't seem to affect the scrollview's zoomScale. It seems that the scrollview's zoomScale depends on the effects of setTransform, but I cannot determine how.
Any assistance would be greatly appreciated.
What you will need to do is update the contentScaleFactor of the chartView. You can do that by adding the following code in either scrollViewDidEndZooming:withView:atScale: or scrollViewDidZoom:.
CGFloat newScale = scrollView.zoomScale * [[UIScreen mainScreen] scale];
[self.chartView setContentScaleFactor:newScale];
I have figured out a solution to my problem that is not too gross a hack. In your UIScrollViewDelegate:
- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
{
[_contentView beginZoom];
}
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
{
CGSize size = scrollView.bounds.size;
CGPoint contentOffset = _scrollView.contentOffset;
CGFloat newScale = _contentView.scale;
newScale = MAX(newScale, kMinZoomScale);
newScale = MIN(newScale, kMaxZoomScale);
[_scrollView setZoomScale:1.0 animated:NO];
_scrollView.minimumZoomScale = kMinZoomScale / newScale;
_scrollView.maximumZoomScale = kMaxZoomScale / newScale;
_contentView.scale = newScale;
CGSize newContentSize = CGSizeMake(size.width * newScale, size.height);
_contentView.frame = CGRectMake(0, 0, newContentSize.width, newContentSize.height);
_scrollView.contentSize = newContentSize;
[_scrollView setContentOffset:contentOffset animated:NO];
[_contentView updateForNewSize];
[_contentView setNeedsDisplay];
}
In your content view, declare a scale property and the following methods:
- (void)beginZoom
{
_sizeAtZoomStart = CGSizeApplyAffineTransform(self.frame.size, CGAffineTransformMakeScale(1/self.scale, 1));
_scaleAtZoomStart = self.scale;
}
- (void)setTransform:(CGAffineTransform)transform
{
self.scale = _scaleAtZoomStart * transform.a;
self.frame = CGRectMake(0, 0, _sizeAtZoomStart.width * self.scale, _sizeAtZoomStart.height);
[self updateForNewSize];
[self setNeedsDisplay];
}
And if your content view uses sub-layers, you'll need to disable their implicit animations by adding the following to the sub-layers' delegate(s):
- (id<CAAction>)actionForLayer:(CALayer *)layer forKey:(NSString *)event
{
// prevent animation of the individual layers so that zooming doesn't cause weird jitter
return (id<CAAction>)[NSNull null];
}
The basic idea here is that the overridden setTransform uses the scale factor from the tranform matrix to calculate the new scale factor for the content view and then resizes the content view accordingly. The scrollview automatically adjusts the content offset to keep the content view centered.
The scrollViewDidEndZooming code keeps the zooming bounded.
There are further complexities for dealing with resizing the scrollview when rotating device for example.

UIScrollView setZoomScale sets the applied rotation back to Zero

I've been working on a maps replacement for quite a while now. The whole thing works with a UIScrollView backed by a CATiledLayer.
To rotate my map, i rotate the layer itself. (Using CATransform3DMakeRotation) Works pretty well so far =)
But if I ever call setZoomScale method the CATransform3D that is going to be submitted to my layer is resetting the rotation to 0.
My question is, is there any way to set the zoomscale of my scrollView without loosing the applied rotation?
The same problem exists for the pinch gestures.
//Additional Infos
To rotate around the current Position, i have to edit the anchor point. Maybe this is a problem for the scaling, too.
- (void)correctLayerPosition {
CGPoint position = rootView.layer.position;
CGPoint anchorPoint = rootView.layer.anchorPoint;
CGRect bounds = rootView.bounds;
// 0.5, 0.5 is the default anchorPoint; calculate the difference
// and multiply by the bounds of the view
position.x = (0.5 * bounds.size.width) + (anchorPoint.x - 0.5) * bounds.size.width;
position.y = (0.5 * bounds.size.height) + (anchorPoint.y - 0.5) * bounds.size.height;
rootView.layer.position = position;
}
- (void)onFinishedUpdateLocation:(CLLocation *)newLocation {
if (stayOnCurrentLocation) {
[self scrollToCurrentPosition];
}
if (rotationEnabled) {
CGPoint anchorPoint = [currentConfig layerPointForLocation:newLocation];
anchorPoint.x = anchorPoint.x / rootView.bounds.size.width;
anchorPoint.y = anchorPoint.y / rootView.bounds.size.height;
rootView.layer.anchorPoint = anchorPoint;
[self correctLayerPosition];
}
}
You can implement scrollViewDidZoom: delegate method and concatenate the two transforms to achieve desired effect:
- (void) scrollViewDidZoom:(UIScrollView *) scrollView
{
CATransform3D scale = contentView.layer.transform;
CATransform3D rotation = CATransform3DMakeRotation(M_PI_4, 0, 0, 1);
contentView.layer.transform = CATransform3DConcat(rotation, scale);
}
EDIT
I've got simpler idea! How about adding another view to the hierarchy with the rotation transform attached? Here's the proposed hierarchy:
ScrollView
ContentView - the one returned by viewForZoomingInScrollView:
RotationView - the one with rotation transform
MapView - the one with all the tiles
I don't think that performance should be any concern here and it's worth trying.

Resources