iOS Layer animation with auto layout - ios

I have a simple container view(green) and two sub views(red and blue) as below.
The container view is not applying auto layout and I config its size & location by frame.
While the sub views are applying auto layout(see code below)
#implementation XXView {
UIView *_leftView;
UIView *_rightView;
}
- (instancetype)init {
self = [super initWithFrame:CGRectZero];
if (self) {
[self setupViewHierarchy];
[self setupConstraints];
}
return self;
}
- (void)setupViewHierarchy {
_leftView = [[UIView alloc] init];
_leftView.backgroundColor = UIColor.redColor;
_leftView.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:_leftView];
_rightView = [[UIView alloc] init];
_rightView.backgroundColor = UIColor.blueColor;
_rightView.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:_rightView];
self.backgroundColor = UIColor.greenColor;
}
- (void)setupConstraints {
[NSLayoutConstraint activateConstraints:#[
[_leftView.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:10],
[_leftView.topAnchor constraintEqualToAnchor:self.topAnchor],
[_leftView.bottomAnchor constraintEqualToAnchor:self.bottomAnchor],
[_leftView.widthAnchor constraintEqualToConstant:50],
[_rightView.trailingAnchor constraintEqualToAnchor:self.trailingAnchor constant:-10],
[_rightView.topAnchor constraintEqualToAnchor:_leftView.topAnchor],
[_rightView.bottomAnchor constraintEqualToAnchor:_leftView.bottomAnchor],
[_rightView.widthAnchor constraintEqualToAnchor:_leftView.widthAnchor],
]];
}
...
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
XXView *tv = [[XXView alloc] init];
CGFloat width = self.view.bounds.size.width;
tv.frame = CGRectMake(50, 400, width-100, 100);
[self.view addSubview:tv];
self.tv = tv;
}
Then I would like to animate the container's width change by using the CABasicAnimation as below:
- (void)startAnimation {
[CATransaction begin];
CGFloat width = self.bounds.size.width;
CABasicAnimation *widthAnimation = [CABasicAnimation animationWithKeyPath:#"bounds.size.width"];
widthAnimation.fromValue = #(width/2);
widthAnimation.toValue = #(width);
widthAnimation.duration = 1;
[self.layer addAnimation:widthAnimation forKey:#"123"];
[CATransaction commit];
}
However, the animation is not as I would expect. I would expect the left view moves as the container's leading side and the right view does as the trailing side.
What I see is, the green view expands as expected and the left view moves as green view's leading side. However, the right view is always keeping the same distance to left view. Below is the screenshot taken at the beginning of the animation.
Why the animation is not working as expected?

The problem is that your CABasicAnimation is modifying the bounds of the layer ... but as far as auto-layout is concerned that does not change the width of the view.
It's not really clear what your goal is here, but if you change your animation method to this it might get you on your way:
- (void)startAnimation {
CGRect f = self.frame;
CGFloat fw = f.size.width;
f.size.width = fw / 2;
self.frame = f;
[self layoutIfNeeded];
f.size.width = fw;
[UIView animateWithDuration:1.0 animations:^{
self.frame = f;
[self layoutIfNeeded];
}];
}

Related

How do I add both shadow and rounded corners to a UIVisualEffectView?

I'm using a container for elements which I'd like for it to be blurred. In order to add rounded corners I modified the layer while for the shadow I created a second view named containerShadow and placed it below it.
It works, but not flawlessly. The shadow darkens the effect of the blur. Is there a way to perfect it?
.h
#property (strong) UIVisualEffectView *containerView;
#property (strong) UIView *containerShadowView;
.m
- (instancetype)init {
if (self = [super init]) {
self.containerShadowView = [[UIView alloc] init];
self.containerShadowView.layer.masksToBounds = NO;
self.containerShadowView.layer.shadowRadius = 80.0;
self.containerShadowView.layer.shadowColor = [[UIColor blackColor] CGColor];
self.containerShadowView.layer.shadowOffset = CGSizeZero;
self.containerShadowView.layer.shadowOpacity = 0.25;
[self addSubview:self.containerShadowView];
self.containerView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
self.containerView.clipsToBounds = YES;
self.containerView.layer.cornerRadius = 20.0;
[self addSubview:self.containerView];
}
return self;
}
- (void)setFrame:(CGRect)frame {
[super setFrame:frame];
// Random container frame for testing...
self.containerView.frame =
CGRectMake(20.0,
200.0,
380,
480);
self.containerShadowView.frame = self.containerView.frame;
self.containerShadowView.layer.shadowPath =
[[UIBezierPath bezierPathWithRoundedRect:self.containerShadowView.bounds cornerRadius:self.containerView.layer.cornerRadius] CGPath];
}
You can do this by masking your containerShadowView with a "cutout" that matches the containerView effect view.
So, this is how it looks - I centered the 380x480 view, and used 0.9 for the .shadowOpacity to emphasize the differences.
Your original on the left, masked version on the right:
Kinda difficult to tell what's really going on, since that could be an opaque layer, we'll add a label behind it:
and, to clarify what we're doing, let's look at it with the containerView effect view hidden:
Here's the source code I used for that - each tap anywhere will cycle through the 8 different layouts:
#import <UIKit/UIKit.h>
#interface OrigShadowView : UIView
#property (strong) UIVisualEffectView *containerView;
#property (strong) UIView *containerShadowView;
#end
#implementation OrigShadowView
- (instancetype)init {
if (self = [super init]) {
self.containerShadowView = [[UIView alloc] init];
self.containerShadowView.layer.masksToBounds = NO;
self.containerShadowView.layer.shadowRadius = 80.0;
self.containerShadowView.layer.shadowColor = [[UIColor blackColor] CGColor];
self.containerShadowView.layer.shadowOffset = CGSizeZero;
self.containerShadowView.layer.shadowOpacity = 0.9;
[self addSubview:self.containerShadowView];
self.containerView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
self.containerView.clipsToBounds = YES;
self.containerView.layer.cornerRadius = 20.0;
[self addSubview:self.containerView];
}
return self;
}
- (void)setFrame:(CGRect)frame {
[super setFrame:frame];
// let's center a 380 x 480 rectangle in self
CGFloat w = 380.0;
CGFloat h = 480.0;
CGRect vRect = CGRectMake((frame.size.width - w) * 0.5, (frame.size.height - h) * 0.5, w, h);
self.containerView.frame = vRect;
self.containerShadowView.frame = self.containerView.frame;
// change origin to 0,0 because the following will be relative to the subviews
vRect.origin = CGPointZero;
self.containerShadowView.layer.shadowPath =
[[UIBezierPath bezierPathWithRoundedRect:vRect cornerRadius:self.containerView.layer.cornerRadius] CGPath];
}
#end
#interface MaskShadowView : UIView
#property (strong) UIVisualEffectView *containerView;
#property (strong) UIView *containerShadowView;
#end
#implementation MaskShadowView
- (instancetype)init {
if (self = [super init]) {
self.containerShadowView = [[UIView alloc] init];
self.containerShadowView.layer.masksToBounds = NO;
self.containerShadowView.layer.shadowRadius = 80.0;
self.containerShadowView.layer.shadowColor = [[UIColor blackColor] CGColor];
self.containerShadowView.layer.shadowOffset = CGSizeZero;
self.containerShadowView.layer.shadowOpacity = 0.9;
[self addSubview:self.containerShadowView];
self.containerView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
self.containerView.clipsToBounds = YES;
self.containerView.layer.cornerRadius = 20.0;
[self addSubview:self.containerView];
}
return self;
}
- (void)setFrame:(CGRect)frame {
[super setFrame:frame];
// let's center a 380 x 480 rectangle in self
CGFloat w = 380.0;
CGFloat h = 480.0;
CGRect vRect = CGRectMake((frame.size.width - w) * 0.5, (frame.size.height - h) * 0.5, w, h);
self.containerView.frame = vRect;
self.containerShadowView.frame = self.containerView.frame;
// change origin to 0,0 because the following will be relative to the subviews
vRect.origin = CGPointZero;
self.containerShadowView.layer.shadowPath =
[[UIBezierPath bezierPathWithRoundedRect:vRect cornerRadius:self.containerView.layer.cornerRadius] CGPath];
UIBezierPath *bigBez;
UIBezierPath *clipBez;
// we need a rectangle that will encompass the shadow radius
// double the shadowRadius is probably sufficient, but since it won't be seen
// and won't affect anything else, we'll make it 4x
CGRect expandedRect = CGRectInset(vRect, -self.containerShadowView.layer.shadowRadius * 4.0, -self.containerShadowView.layer.shadowRadius * 4.0);
bigBez = [UIBezierPath bezierPathWithRect:expandedRect];
// we want to "clip out" a rounded rect in the center
// which will be the same size as the visual effect view
clipBez = [UIBezierPath bezierPathWithRoundedRect:vRect cornerRadius:self.containerView.layer.cornerRadius];
[bigBez appendPath:clipBez];
bigBez.usesEvenOddFillRule = YES;
CAShapeLayer *maskLayer = [CAShapeLayer new];
maskLayer.fillRule = kCAFillRuleEvenOdd;
maskLayer.fillColor = UIColor.whiteColor.CGColor;
maskLayer.path = bigBez.CGPath;
self.containerShadowView.layer.mask = maskLayer;
}
#end
#interface BlurTestViewController : UIViewController
{
OrigShadowView *origView;
MaskShadowView *newView;
UILabel *bkgLabel;
// so we can step through on taps to see the results
NSInteger step;
UILabel *infoLabel;
}
#end
#implementation BlurTestViewController
- (void)viewDidLoad {
[super viewDidLoad];
bkgLabel = [UILabel new];
bkgLabel.textColor = UIColor.blueColor;
bkgLabel.font = [UIFont systemFontOfSize:48.0 weight:UIFontWeightBlack];
bkgLabel.textAlignment = NSTextAlignmentCenter;
bkgLabel.numberOfLines = 0;
bkgLabel.text = #"A label can contain an arbitrary amount of text, but UILabel may shrink, wrap, or truncate the text, depending on the size of the bounding rectangle and properties you set. You can control the font, text color, alignment, highlighting, and shadowing of the text in the label.";
bkgLabel.text = #"I'm using a container for elements which I'd like for it to be blurred. In order to add rounded corners I modified the layer while for the shadow I created a second view named containerShadow and placed it below it.";
origView = [OrigShadowView new];
newView = [MaskShadowView new];
[self.view addSubview:bkgLabel];
[self.view addSubview:origView];
[self.view addSubview:newView];
infoLabel = [UILabel new];
infoLabel.font = [UIFont systemFontOfSize:20.0 weight:UIFontWeightBold];
infoLabel.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:infoLabel];
step = 0;
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
// let's inset the "shadow blur" views 40-points
CGRect r = CGRectInset(self.view.frame, 40.0, 40.0);
origView.frame = r;
newView.frame = r;
// let's put the background label midway down the screen
r.origin.y += r.size.height * 0.5;
r.size.height *= 0.5;
bkgLabel.frame = r;
// put the info label near the top
infoLabel.frame = CGRectMake(40.0, 80.0, r.size.width, 40.0);
[self nextStep];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self nextStep];
}
- (void)nextStep {
bkgLabel.hidden = YES;
origView.hidden = YES;
newView.hidden = YES;
origView.containerView.hidden = NO;
newView.containerView.hidden = NO;
step++;
switch (step) {
case 1:
origView.hidden = NO;
infoLabel.text = #"1: Original View";
break;
case 2:
newView.hidden = NO;
infoLabel.text = #"2: Masked View";
break;
case 3:
bkgLabel.hidden = NO;
origView.hidden = NO;
infoLabel.text = #"3: Original View";
break;
case 4:
bkgLabel.hidden = NO;
newView.hidden = NO;
infoLabel.text = #"4: Masked View";
break;
case 5:
origView.hidden = NO;
origView.containerView.hidden = YES;
infoLabel.text = #"5: Original View - effect view hidden";
break;
case 6:
newView.hidden = NO;
newView.containerView.hidden = YES;
infoLabel.text = #"6: Masked View - effect view hidden";
break;
case 7:
bkgLabel.hidden = NO;
origView.hidden = NO;
origView.containerView.hidden = YES;
infoLabel.text = #"7: Original View - effect view hidden";
break;
default:
bkgLabel.hidden = NO;
newView.hidden = NO;
newView.containerView.hidden = YES;
infoLabel.text = #"8: Masked View - effect view hidden";
step = 0;
break;
}
}
#end

Graphics drawing in a custom UIView don't work in the third view

I am trying to repurpose this plotting widget, and in particular I am trying to put 3 plots in one custom UIViewController. I am finding that the first two I process/add to my self.view are fine, but for the third view the following doesn't work
-(void) drawLineFrom:(CGPoint) start to: (CGPoint)end {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(context, start.x, start.y);
CGContextAddLineToPoint(context,end.x,end.y);
}
- (void)drawRect:(CGRect)rect
{
...
if([self.dictDispPoint count] > 0)
{
// remove loading animation
[self stopLoading];
float range = self.max-self.min;
float intervalHlines = (self.chartHeight)/MIN(intervalLines, self.dictDispPoint.count - 1); //5.0f;
float intervalValues = range/MIN(intervalLines, self.dictDispPoint.count - 1); //5.0f;
// horizontal lines
for(int i=intervalLines;i>0;i--)
{
[self setContextWidth:0.5f andColor:linesColor];
CGPoint start = CGPointMake(self.leftMargin, (self.chartHeight+topMargin-i*intervalHlines-6));
CGPoint end = CGPointMake(self.chartWidth+self.leftMargin, (self.chartHeight+topMargin-i*intervalHlines-6));
// draw the line
[self drawLineFrom:start to:end]; // This line doesn't seem to run?!?
// draw prices on the axis
NSString *prezzoAsse = [self formatNumberWithUnits:(self.min+i*intervalValues)/valueDivider withFractionDigits:0];
CGPoint prezzoAssePoint = CGPointMake(self.leftMargin - [self sizeOfString:prezzoAsse withFont:systemFont].width - 5,(self.chartHeight+topMargin-i*intervalHlines-6));
[self drawString:prezzoAsse at:prezzoAssePoint withFont:systemFont andColor:linesColor];
[self endContext];
}
...
}
In particular, I have verified that the for loop runs the requisite number of times and that all the variables have non-null sensible values. And the drawString function is working as expected, but somehow the horizontal lines I should be seeing never show up in the third instance of this custom view class.
Printing all variable + line color...these are all non-null, sensible
Changing the order of the graphs...it's always the 3rd graph (haven't tried more than 3) that has a problem
Changing the data in the graph...the problem is there regardless of what data I supply to make the graph
Cleaning the build, trying different iPhones in the simular...yup, this doesn't change the performance
I don't have much experience with Quartz. Can anyone tell me if I am missing some traps for the unweary? Is there some threading problem when multiple views are draw simultaneously? What else could I try to trouble-shoot this?
Here is code showing how the plots are created and laid out on the screen:
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Your recent runs";
/********** Creating an area for the graph ***********/
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
self.width = screenWidth;
self.height = screenRect.size.height;
CGRect frame = CGRectMake(0, self.height*.15, screenWidth, self.height*.25);
// initialization
self.distancePlot = [[ZFPlotChart alloc] initWithFrame:frame];
self.distancePlot.units = self.distanceUnits;
[self.view addSubview:self.distancePlot];
frame.origin.y += self.height*.05 + frame.size.height;
self.timePlot = [[ZFPlotChart alloc] initWithFrame:frame];
self.timePlot.units = self.timeUnits;
[self.view addSubview:self.timePlot];
//THIS IS THE PLOT FOR WHICH THE LINE-DRAWING CODE DOESN'T PRODUCE ANY VISIBLE LINES
frame.origin.y += self.height*.05 + frame.size.height;
self.ratePlot = [[ZFPlotChart alloc] initWithFrame:frame];
self.ratePlot.units = self.rateUnits;
[self.view addSubview:self.ratePlot];
self.distancePlot.alpha = 0;
self.timePlot.alpha = 0;
self.ratePlot.alpha = 0;
CGFloat heightAdd = frame.size.height;
frame = CGRectMake(0, self.height*.14, self.width, self.height*.03);
...some here creates UILabels above each plot....
frame.origin.y += self.height*.05 + heightAdd;
UILabel *rateLabel = [[UILabel alloc] initWithFrame:frame];
rateLabel.text = #"Rate";
rateLabel.textColor = [UIColor darkBlue];
rateLabel.alpha = 0;
rateLabel.font = [UIFont fontWithName:SYSTEM_FONT_TYPE size:SYSTEM_FONT_SIZE];
rateLabel.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:rateLabel];
// draw data
[self.distancePlot createChartWith:self.distancePoints];
[self.timePlot createChartWith:self.timePoints];
[self.ratePlot createChartWith:self.ratePoints];
[UIView animateWithDuration:0.5 animations:^{
self.distancePlot.alpha = 1.0;
self.timePlot.alpha = 1.0;
self.ratePlot.alpha = 1.0;
distanceLabel.alpha = 1.0;
timeLabel.alpha = 1.0;
rateLabel.alpha = 1.0;
}];
}

updating custom uiview's frame after adding subviews to it

I am having a big mental block figuring out something I think easy. Please see this very short video: http://screencast.com/t/eaW7rbECv4Ne.
I would like to draw a rectangle in my layoutSubviews method around the whole area that covers the subviews. I currently draw yellow rect around each term as you can see in the video.
I have a StatementView. In each key tap I am creating new objectView and adding it to my StatementView like below. I add the objectViews to a containerView and try to get the origin and size of the containerView in order to draw the stroke around it. However, it always gives me 0.
How should I update containerViews bounds values after I add the subviews to it?
// Created by ilteris on 1/31/15.
// Copyright (c) 2015 ilteris. All rights reserved.
#implementation QWZStatementView
-(id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.userInteractionEnabled = NO;
self.textField = [[MyUITextField alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
self.textField.inputView = [LNNumberpad defaultLNNumberpad];
self.textField.delegate = self;
self.isNumerator = NO;
self.isDenominator = NO;
[self addSubview:self.textField];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(statementOneTextFieldChanged:) name:UITextFieldTextDidChangeNotification object:nil];
self.containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
[self addSubview:self.containerView];
self.autoresizesSubviews = YES;
self.objectsArray = [NSMutableArray arrayWithCapacity:1];
self.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
}
return self;
}
-(void)statementOneTextFieldChanged:(NSNotification *)notification {
NSLog(#"statementOneTextFieldChanged");
QWZObjectView *objectView = [[QWZObjectView alloc] initWithFrame:self.bounds];
[self.containerView addSubview:objectView];
QWZTerm* term = [QWZQuestionDetailViewController createAndReturnCoreDataTermForJSONDict:objectData];
[objectView createTerm:term];
[self.objectsArray addObject:objectView];
[self setNeedsLayout];
}
- (void)layoutSubviews {
NSLog(#"layoutSubviews StatementView");
[super layoutSubviews];
CGSize totalSize = CGSizeMake(0, 0);
for (QWZObjectView* objectView in self.objectsArray) {
CGSize textSize = objectView.bounds.size;
objectView.frame = CGRectMake(totalSize.width , totalSize.height, textSize.width , textSize.height);
totalSize.width = textSize.width + totalSize.width;
}
CGRect bounds = self.containerView.bounds;
/*
NSLog(#"self.containerView.bounds is %#", NSStringFromCGRect(self.containerView.bounds)); //always 0.
bounds.origin = CGPointMake(totalSize.width/2, self.containerView.bounds.origin.y); //adding this code didn't help at all.
CGFloat borderWidth = 2.0f;
self.bounds = CGRectInset(self.bounds, -borderWidth, -borderWidth);
self.layer.borderColor = [UIColor redColor].CGColor;
self.layer.borderWidth = borderWidth;
*/
bounds.origin = CGPointMake(totalSize.width/2, self.containerView.bounds.origin.y);
self.containerView.bounds = bounds;
}
#end

UIView Animation for ImageView in ios

i Have requirement were i have to animate image view from current position to full screen in grid view. i made images into Grid view.
- (void)viewDidLoad
{
[super viewDidLoad];
imagesArray = [[NSMutableArray alloc] init];
for (int i=1; i<11; i++) {
[imagesArray addObject:[UIImage imageNamed:[NSString stringWithFormat:#"image%d.png", i]]];
NSLog(#"imagesArray:%#", imagesArray);
}
float horizontal = 20.0;
float vertical = 20.0;
for(int i=0; i<[imagesArray count]; i++)
{
if((i%3) == 0 && i!=0)
{
horizontal = 20.0;
vertical = vertical + 220.00 + 20.0;
}
imagesView = [[UIImageView alloc] initWithFrame:CGRectMake(horizontal, vertical, 310.0, 220.00)];
imagesView.userInteractionEnabled = YES;
[imagesView setImage:[imagesArray objectAtIndex:i]];
imagesView.tag = i;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTap:)];
tap.numberOfTapsRequired = 1;
tap.numberOfTouchesRequired = 1;
[imagesView addGestureRecognizer:tap];
[self.view addSubview:imagesView];
horizontal = horizontal + 310.0 + 20.0;
}
}
here i have created grid view with images, like i have 10 images. i made 3x3 grid view.
next i have add tap gesture to it and i am getting the image view position by calling with tag
-(void)handleTap:(UITapGestureRecognizer *)recognizer
{
UIView *piece = recognizer.view;
[UIView animateWithDuration:1.0 animations:^{
piece.frame = CGRectMake(piece.frame.origin.x, piece.frame.origin.y, 1000, 700);
} completion:^(BOOL finished) {
}];
}
Can you say me how to make image view animate from current position to full screen by tapping on it.
Since you're adding the views to self.view of your view controller, you can assume that self.view is occupying the entire screen of the device. Therefore, you can animate to its bounds:
[UIView animateWithDuration:1.0 animations:^{
piece.frame = self.view.bounds;
} completion:nil];
Note that if piece must have a parent view that spans across the entire screen so that your inner view won't be clipped during animation.
This code will help u to add the animation effect like zoom your imageview that your are expecting. You need to customize once the animation is over show the full screen image view.
-(void)addZoomAnimationToZoomViewController:(UIImageView *)zoomView
{
CABasicAnimation *zoomAnimation = [CABasicAnimation animationWithKeyPath:#"transform.scale"];
[zoomAnimation setDuration:0.8];
[zoomAnimation setRepeatCount:1];
[zoomAnimation setFromValue: [NSNumber numberWithFloat:0.1]];
[zoomAnimation setToValue: [NSNumber numberWithFloat:5.0] ];
[zoomAnimation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
[[zoomView layer] addAnimation:zoomAnimation forKey:#"zoom"];
}

UIScrollView squashes UIImageView image

I have the following code in ViewDidLoad and it squashes my UIImage/ UIImageView. I want the image to fill the UIScrollView.
[super viewDidLoad];
_imageHolder = [[UIImageView alloc]initWithFrame:self.view.frame];
_scrollView = [[UIScrollView alloc]initWithFrame:self.view.frame];
[_scrollView setBackgroundColor:[UIColor purpleColor]];
// Tell the scroll view the size of the contents
self.scrollView.contentSize = self.view.frame.size;
self.scrollView.delegate = self;
self.scrollView.scrollEnabled = YES;
FfThumbnailData* thumbData = [self.arrayOfImages objectAtIndex:self.thisImageIndex];
UIImage* fullSizedImage = [[UIImage alloc]initWithContentsOfFile:thumbData.path];
[self.imageHolder setImage:fullSizedImage];
float x = fullSizedImage.size.width;
float y = fullSizedImage.size.height;
CGRect rect = CGRectMake(0, 0, x, y);
NSLog(#"Size of image: %#", NSStringFromCGRect(rect));
//
//[self.imageHolder setImage:[UIImage imageNamed:#"P1020486.png"]];
[self.scrollView addSubview:_imageHolder];
[self.view addSubview:self.scrollView];
_imageHolder.contentMode = UIViewContentModeScaleAspectFit;
I set the backgound of the UIScrollView to purple for clarity:
http://i1219.photobucket.com/albums/dd427/Dave_Chambers/IMG_0315.png
I should add that after I zoom in and then zoom out, the image IS correctly placed in the scrollview and not squashed.
Strangely, the commented line [self.imageHolder setImage:[UIImage imageNamed:#"P1020486.png"]]; correctly displays the dummy image P1020486.png.
Also, when I download my app data, the image looks right and is indeed the correct size of an iPad image - {1936, 2592} - the size reported by my NSLog line NSLog(#"Size of image: %#", NSStringFromCGRect(rect));
Further, before I needed a UIScrollView (for zooming the photo in the full size View Controller) I access the same image and display it via an animation from one View Controller to another with the following code and it displays correctly. Crucially thought, this second section of code lacks a UIScollview.
-(void)animateTransition:(int)buttonInPositon {
#try {
FfThumbnailData* thumbData = [self.images objectAtIndex:buttonInPositon];
UIImage* fullSizedImage = [[UIImage alloc]initWithContentsOfFile:thumbData.path];
fullSize = [[FullSizeViewController alloc]init];
fullSize.imageHolderGhost.contentMode = UIViewContentModeScaleAspectFit;
fullSize.arrayOfImages = self.images;
fullSize.imageToPresent = fullSizedImage;
fullSize.numberOfImages = self.images.count;
fullSize.thisImageIndex = buttonInPositon;
[fullSize.imageHolderGhost setImage:fullSizedImage];
float screenWidth = self.view.bounds.size.width;
float screenHeight = self.view.bounds.size.height;
NSLog(#"ButtonFrame: %#", NSStringFromCGRect(buttonFrame));
[fullSize.view setFrame:CGRectMake(buttonFrame.origin.x, buttonFrame.origin.y, buttonFrame.size.width, buttonFrame.size.height-44)];
NSLog(#"ButtonFrame: %#", NSStringFromCGRect(fullSize.view.frame));
[self.view addSubview:fullSize.view];
fullSize.view.backgroundColor = [UIColor clearColor];
[UIView animateWithDuration:0.9 delay:0 options:UIViewAnimationCurveEaseIn animations:^{
[fullSize.view setFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
} completion:^(BOOL finished){
[[self navigationController] pushViewController:fullSize animated:NO];
self.navigationController.navigationBarHidden = YES;
}];
}
#catch (NSException *exception) {
NSLog(#"%#", exception);
}
}
For completeness, the code with the UIScrollView has the following method in one VC:
-(void)presentWithScrollview:(int)buttonInPositon {
FfThumbnailData* thumbData = [self.images objectAtIndex:buttonInPositon];
UIImage* fullSizedImage = [[UIImage alloc]initWithContentsOfFile:thumbData.path];
fullSize = [[FullSizeViewController alloc]init];
fullSize.arrayOfImages = self.images;
fullSize.imageToPresent = fullSizedImage;
fullSize.numberOfImages = self.images.count;
fullSize.thisImageIndex = buttonInPositon;
[[self navigationController] pushViewController:fullSize animated:NO];
self.navigationController.navigationBarHidden = YES;
}
and in the destination VC the following methods may be relevant to my problem (ViewDidLoad pasted at the top of this question):
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// Set up the minimum & maximum zoom scales
CGRect scrollViewFrame = self.scrollView.frame;
CGFloat scaleWidth = scrollViewFrame.size.width / self.scrollView.contentSize.width;
CGFloat scaleHeight = scrollViewFrame.size.height / self.scrollView.contentSize.height;
CGFloat minScale = MIN(scaleWidth, scaleHeight);
//
self.scrollView.minimumZoomScale = minScale;
//Can set this bigger if needs be - match iPhoto
self.scrollView.maximumZoomScale = 2.0f;
[self centerScrollViewContents];
}
- (void)centerScrollViewContents {
CGSize boundsSize = self.scrollView.bounds.size;
//NSLog(#"boundsSize: %#", NSStringFromCGSize(boundsSize));
CGRect contentsFrame = self.imageHolder.frame;
//NSLog(#"contentsFrame: %#", NSStringFromCGRect(contentsFrame));
if (contentsFrame.size.width < boundsSize.width) {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
} else {
contentsFrame.origin.x = 0.0f;
}
if (contentsFrame.size.height < boundsSize.height) {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
} else {
contentsFrame.origin.y = 0.0f;
}
self.imageHolder.frame = contentsFrame;
}
#pragma mark - UIScrollViewDelegate
- (UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView {
// Return the view that we want to zoom
return self.imageHolder;
//return self.scrollViewBar;
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
// The scroll view has zoomed, so we need to re-center the contents
[self centerScrollViewContents];
}
Any help on this would be great. Thanks
So, I found the solution myself. For some reason, as I wrote in my update to the question, any zooming in, followed by zooming out of the image fixed the image problem and presented it properly. I added these two lines to viewWillAppear, above [self centerScrollViewContents];
self.scrollView.zoomScale = 2.0;
self.scrollView.zoomScale = 1.0;
Problem solved

Resources