Getting proper perspective with multiple UIViews - uiview

I want to achieve a proper perspective "tilt" on two separate side-by-side UIView squares. In the image below the red and green squares are separate UIViews with the same transform applied. Visually this perspective is incorrect (is it?), or at least the superior illusion is shown by the Yellow/Blue square UIViews. The Yellow-Blue squares are actually subviews of a rectangular parent UIView, and the transform was applied to the parent view.
Here's the code:
#interface PEXViewController ()
#property (strong, nonatomic) IBOutlet UIView *redSquare;
#property (strong, nonatomic) IBOutlet UIView *greenSquare;
#property (strong, nonatomic) IBOutlet UIView *yellowSquareBlueSquare;
#end
#implementation PEXViewController
#define TILT_AMOUNT 0.65
-(void)tiltView:(UIView *)slave{
CATransform3D rotateX = CATransform3DIdentity;
rotateX.m34 = -1 / 500.0;
rotateX = CATransform3DRotate(rotateX, TILT_AMOUNT * M_PI_2, 1, 0, 0);
slave.layer.transform = rotateX;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self tiltView:self.greenSquare];
[self tiltView:self.redSquare];
[self tiltView:self.yellowSquareBlueSquare];
}
#end
1) Is there a simple way to apply a transform(s) to the separate red/green UIViews and achieve the same effect as the "grouped" yellow and blue UIViews? I prefer to keep the views separate, as this is a universal app and the UIViews are not side-by-side in (e.g.) the iPad layout.
2) If #1 is not possible, I am guessing the best thing to do is simply create a parent view that is present in say iPhone, but not present in iPad. Any other alternatives?

I opted for solution #2. I created a short routine that calculates a bounding box based on an array of UIViews, creates a new parent view from the bounding box, then adds the arrayed views as children. I then can apply the transform to the parent view for the desired effect. Here's the code for gathering and adopting children subviews.
-(UIView *)makeParentWithSubviews:(NSArray *)arrayOfViews{
// Creating a bounding box UIView and add the passed UIViews as subview
// "in-place".
CGFloat xMax = -HUGE_VALF;
CGFloat xMin = HUGE_VALF;
CGFloat yMax = -HUGE_VALF;
CGFloat yMin = HUGE_VALF;
for (UIView *myView in arrayOfViews) {
xMin = MIN(xMin, myView.frame.origin.x);
xMax = MAX(xMax, myView.frame.origin.x + myView.frame.size.width);
yMin = MIN(yMin, myView.frame.origin.y);
yMax = MAX(yMax, myView.frame.origin.y + myView.frame.size.height);
}
CGFloat parentWidth = xMax - xMin;
CGFloat parentHeight = yMax - yMin;
CGRect parentFrame = CGRectMake(xMin, yMin, parentWidth, parentHeight);
UIView *parentView = [[UIView alloc] initWithFrame:parentFrame];
// Replace each child's frame
for (UIView *myView in arrayOfViews){
myView.frame = [[myView superview] convertRect:myView.frame toView:parentView];
[myView removeFromSuperview];
[parentView addSubview:myView];
}
parentView.backgroundColor = [UIColor clearColor];
[self.view addSubview:parentView];
return parentView;
}

Related

How can I add a gradient that spans two views?

I know how to do (1) but how can I do (2)?
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = #[(id)[UIColor blueColor].CGColor, (id)[UIColor redColor].CGColor];
[view.layer insertSublayer:gradient atIndex:0];
There are several ways you could do this. Here's one way:
Create a UIView subclass named GradientView to manage the gradient layer. This is helpful because it means you can use the normal UIKit techniques to manage the gradient layout (auto layout constraints, autoresizing masks, UIKit animations).
For each view that should participate in the common gradient, add a GradientView subview. Set up each GradientView's colors, locations, and start and end points identically.
For each view that should participate in the common gradient, turn on clipsToBounds.
Use auto layout constraints to make each GradientView span all of the participating superviews. (It's important to understand that constraints can cross superview/subview boundaries).
With this approach, auto layout takes care of making the gradient cover all of the views even if they change size or move around. For example, you won't have to do anything special to make the gradients animate nicely when the user rotates the device.
Thus, for your two-view example, I'm proposing that you set up a view hierarchy like this:
In the view debugger screenshot above, I disabled clipping. You can see that the two gradient views have identical gradients and share the same screen space. The topGradient is a subview of topView and bottomGradient is a subview of bottomView.
If we turn clipping on, you'll only see the part of topGradient that fits inside topView's bounds, and you'll only see the part of bottomGradient that fits inside bottomView's bounds. Here's what it looks like with clipping enabled:
And here's a screen shot of my test program in the simulator:
Here's the source code for GradientView:
#interface GradientView: UIView
#property (nonatomic, strong, readonly) CAGradientLayer *gradientLayer;
#end
#implementation GradientView
+ (Class)layerClass { return CAGradientLayer.class; }
- (CAGradientLayer *)gradientLayer { return (CAGradientLayer *)self.layer; }
#end
Here's the code I used to create all of the views:
- (void)viewDidLoad {
[super viewDidLoad];
UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 100, 50)];
topView.layer.cornerRadius = 10;
topView.clipsToBounds = YES;
UIView *topGradient = [self newGradientView];
[topView addSubview:topGradient];
[self.view addSubview:topView];
UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(20, 90, 100, 50)];
bottomView.layer.cornerRadius = 10;
bottomView.clipsToBounds = YES;
UIView *bottomGradient = [self newGradientView];
[bottomView addSubview:bottomGradient];
[self.view addSubview:bottomView];
[self constrainView:topGradient toCoverViews:#[topView, bottomView]];
[self constrainView:bottomGradient toCoverViews:#[topView, bottomView]];
}
- (GradientView *)newGradientView {
GradientView *gv = [[GradientView alloc] initWithFrame:CGRectZero];
gv.translatesAutoresizingMaskIntoConstraints = NO;
gv.gradientLayer.colors = #[(__bridge id)UIColor.blueColor.CGColor, (__bridge id)UIColor.redColor.CGColor];
return gv;
}
And here's how I create the constraints that make a GradientView (or any view) cover a set of views:
- (void)constrainView:(UIView *)coverer toCoverViews:(NSArray<UIView *> *)coverees {
for (UIView *coveree in coverees) {
NSArray<NSLayoutConstraint *> *cs;
cs = #[
[coverer.leftAnchor constraintLessThanOrEqualToAnchor:coveree.leftAnchor],
[coverer.rightAnchor constraintGreaterThanOrEqualToAnchor:coveree.rightAnchor],
[coverer.topAnchor constraintLessThanOrEqualToAnchor:coveree.topAnchor],
[coverer.bottomAnchor constraintGreaterThanOrEqualToAnchor:coveree.bottomAnchor]];
[NSLayoutConstraint activateConstraints:cs];
cs = #[
[coverer.leftAnchor constraintEqualToAnchor:coveree.leftAnchor],
[coverer.rightAnchor constraintEqualToAnchor:coveree.rightAnchor],
[coverer.topAnchor constraintEqualToAnchor:coveree.topAnchor],
[coverer.bottomAnchor constraintEqualToAnchor:coveree.bottomAnchor]];
for (NSLayoutConstraint *c in cs) { c.priority = UILayoutPriorityDefaultHigh; }
[NSLayoutConstraint activateConstraints:cs];
}
}
The greaterThanOrEqual/lessThanOrEqual constraints, which (by default) have required priority, ensure that coverer covers the entire frame of each coveree. The equal constraints, which have lower priority, then ensure that coverer occupies the minimum space required to cover each coveree.
You can do this by adding a view on top of the view with the gradient, then cutting out the shapes by making a mask out of a UIBezierPath, then adding that to the view on top (let's call it topView):
let yourPath: UIBezierPath = //create the desired bezier path for your shapes
let mask = CAShapeLayer()
mask.path = yourPath.cgPath
topView.layer.mask = mask

Clipping rectangular button frame to image mask for use with UIDynamics

I have three buttons on my screen which have background images set in storyboard, the background images are hexagonal shapes. I'm currently playing around with gravity, when a button is pressed I want them all to fall to the bottom of the screen. I would like the buttons to react like they are hexagonal shapes when bouncing off each other rather than the rectangular shapes they are.
Is there a way to clip the UIButtons.frame to the hexagonal.png?
- (IBAction)home:(id)sender {
animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
gravity = [[UIGravityBehavior alloc] initWithItems:#[self.youtuberLyr, self.gameLyr, self.homeLyr]];
[animator addBehavior:gravity];
collision = [[UICollisionBehavior alloc] initWithItems:#[self.youtuberLyr, self.gameLyr, self.homeLyr]];
collision.translatesReferenceBoundsIntoBoundary = YES;
[animator addBehavior:collision];
barrier = [[UIView alloc] initWithFrame:CGRectMake(0, 1024, 768, 0)];
barrier.backgroundColor = [UIColor redColor];
[self.view addSubview:barrier];
CGPoint rightEdge = CGPointMake(barrier.frame.origin.x + barrier.frame.size.width, barrier.frame.origin.y);
[collision addBoundaryWithIdentifier:#"barrier" fromPoint:barrier.frame.origin toPoint:rightEdge];
}
I have tried googling to no avail. Any help is greatly appreciated.
UIKit Dynamics only supports rectangle shapes as defined by this protocol.
#protocol UIDynamicItem <NSObject>
#property (nonatomic, readwrite) CGPoint center;
#property (nonatomic, readonly) CGRect bounds;
#property (nonatomic, readwrite) CGAffineTransform transform;
#end
Maybe SpriteKit's SKPhysicsBody would work for your case. Specifically, by passing a hexagon path to this initializer.
+ (SKPhysicsBody *)bodyWithPolygonFromPath:(CGPathRef)path

UIScrollview - how to make subview smaller as it scrolls off screen

I'm a beginner with iOS, so i'm just not sure what to research here. I have a UIScrollView with a few square subViews added. How can i make the subviews smaller as they scroll off screen and bigger as they approach the center of the screen?
#import "HorizontalScrollMenuViewController.h"
#import <UIKit/UIKit.h>
#define SUBVIEW_WIDTH_HEIGHT 280
#interface HorizontalScrollMenuViewController : UIViewController
#property (nonatomic, strong) IBOutlet UIScrollView *scrollView;
#end
#implementation HorizontalScrollMenuViewController
-(void)viewDidLoad{
[super viewDidLoad];
NSArray *colors = [NSArray arrayWithObjects:[UIColor greenColor],[UIColor redColor],[UIColor orangeColor],[UIColor blueColor],nil ];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
CGFloat originX = (screenWidth - SUBVIEW_WIDTH_HEIGHT)/2.0; // get margin to left and right of subview
CGFloat originY = ((screenHeight - SUBVIEW_WIDTH_HEIGHT)/2);
// add subviews of all activities
for (int i = 0; i < colors.count; i++){
CGRect frame = CGRectMake(0,0,SUBVIEW_WIDTH_HEIGHT,SUBVIEW_WIDTH_HEIGHT);
frame.origin.x = self.scrollView.frame.size.width * i + originX;
frame.origin.y = originY;
UIView *subView = [[UIView alloc] initWithFrame:frame];
[UIView setAnimationBeginsFromCurrentState: YES];
subView.layer.cornerRadius = 15;
subView.layer.masksToBounds = YES;
subView.backgroundColor = [colors objectAtIndex:i];
[self.scrollView addSubview:subView];
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * colors.count, self.scrollView.frame.size.height);
}
#end
Here you can find a fully working example of what you're trying to accomplish. It only has
one subview because it's just to give you an idea of how can you accomplish it. Also, this example was tested on an iPad (iOS7) simulator.
The *.h file
#import <UIKit/UIKit.h>
// Remember to declare ourselves as the scroll view delegate
#interface TSViewController : UIViewController <UIScrollViewDelegate>
#property (nonatomic, strong) UIView *squareView;
#end
The *.m file
#import "TSViewController.h"
#implementation TSViewController
#synthesize squareView = _squareView;
- (void)viewDidLoad
{
[super viewDidLoad];
// Create and configure the scroll view (light gray)
UIScrollView *myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(100, 100, 500, 500)];
CGRect contentSize = myScrollView.frame;
contentSize.size.height = contentSize.size.height + 400;
myScrollView.contentSize = contentSize.size;
myScrollView.userInteractionEnabled = YES;
// give the scroll view a gray color so it's easily identifiable
myScrollView.backgroundColor = [UIColor lightGrayColor];
// remember to set yourself as the delegate of the scroll view
myScrollView.delegate = self;
[self.view addSubview:myScrollView];
// Create and configure the square view (blue)
self.squareView = [[UIView alloc] initWithFrame:CGRectMake(200, 400, 60, 60)];
self.squareView.backgroundColor = [UIColor blueColor];
[myScrollView addSubview:self.squareView];
}
// Here is where all the work happens
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
// Get the difference between the contentOffset y position and the squareView y position
CGFloat y = self.squareView.frame.origin.y - scrollView.contentOffset.y;
// If the square has gone out of view, return
if (y <= 0) {
return;
}
// Modify the squareView's frame depending on it's current position
CGRect squareViewFrame = self.squareView.frame;
squareViewFrame.size.height = y + 5;
squareViewFrame.size.width = y + 5;
squareViewFrame.origin.x = (scrollView.contentSize.width - squareViewFrame.size.width) / 2.0;
self.squareView.frame = squareViewFrame;
}
#end
And here is a little explanation of what is going on:
A UIScrollView has several properties that allow you to configure it correctly. For example it has a frame (gray) which is inherited from UIView; with this property you specify the visible size of the scroll view. It also has the contentSize (red) which specifies the total size of the scroll view; in the image it's showed as the red area but this is only for illustration purposes as it will not be visible in the program. Imagine the scroll view's frame as the window that let's you see only a part of the bigger content the scroll view has.
When the user starts scrolling a gap appears between the top part of the contentSize and the top part of the frame. This gap is known as the contentOffset
Here is the reference to UIScrollView
Here is the reference to UIScrollViewDelegate
Hope this helps!
Assuming that you have the scrollView inside self.view, you can implement scrollViewDidScroll: in the scroll view delegate to find when it is scrolled.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
for (UIView *view in self.scrollView.subviews) {
CGRect frame = [view convertRect:view.frame toView:self.view]; // Contains the frame of view with respect to self.view
}
}
You can them use the frame to resize subviews as you want.
The answer starts with analyzing the UIScrollView Class Reference and it's delegate. In the delegate documentation see the responding to scrolling and dragging section. You should also review the sample code for each. You can create outlets to your subviews and change the subview properties within a uiview animation. These references will give you a good foundation in understanding where you can build the call to animate the subviews.
Here is a link to animating subviews. Additional examples can be found by Googling "uiview subview animation" (without the quotes). If you run into any major issues read the header files first and post some sample code for additional (more precise) help.
Other reference:
UIKit ScrollViews

Setting corner radius on a cell kills UICollectionView's performance

I have a UICollectionView that has only a few cells (about 20). Performance for this collection works great. However, as soon as I try to round the corners of the UICollectionViewCells that are being rendered by this view, my performance takes a significant hit. In my cell's init method, this is the only line I add to cause this:
[self.layer setCornerRadius:15];
Since this is in the init method and I am reusing the cells properly, I don't see why this should be causing me issue.
I have tried adjusting the rasterization and opacity of the sell using multiple combinations of the following, with still no effect:
[self.layer setMasksToBounds:YES];
[self.layer setCornerRadius:15];
[self.layer setRasterizationScale:[[UIScreen mainScreen] scale]];
self.layer.shouldRasterize = YES;
self.layer.opaque = YES;
Is their some setting or trick to improve the performance of a UICollectionView that has cells with rounded corners?
As #Till noted in comments, a prerendered image should solve your performance problem. You can put all the corner rounding, shadowing, and whatever other special effects into that instead of needing CA to render them on the fly.
Prerendered images don't lock you into a static content size, either: look into the UIImage resizable image stuff. (That's still way faster than CA rendering every frame.)
I have found that this is caused entirely because of the call to dequeuereusablecellwithidentifier. Each time this is called, the cell with rounded corners needs to be re-rendered. If the collection view did not remove them from the view when the item scrolled off the screen, then the performance would not be affected (as long as their wasn't too many items in the collection that is). Seems like a double edged sword - both ways have their limits.
There is a code for UIView subclass, which is provide you a view with opaque rounded borders and transparent hole in the middle.
You should create needed view as usual and after that you can add view with hole over your view. Visualisation is here.
It works if you use one-colored background for UICollectionView or UITableView, you can add following subview for each cell:
#interface TPRoundedFrameView : UIView
#property (assign, nonatomic) CGFloat cornerRadius;
#property (strong, nonatomic) UIColor * borderColor;
#end
#implementation TPRoundedFrameView
- (instancetype)init {
if ((self = [super init])) {
self.opaque = NO;
self.backgroundColor = [UIColor clearColor];
}
return self;
}
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
UIBezierPath * path = [UIBezierPath bezierPathWithRect:rect];
UIBezierPath * innerPath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:self.cornerRadius];
[path appendPath:[innerPath bezierPathByReversingPath]];
[self.borderColor set];
[path fill];
}
#end
Example for target cell class:
- (void)awakeFromNib {
[super awakeFromNib];
// creating holed view with rounded corners
self.myRoundedView.backgroundColor = [UIColor whiteColor];
TPRoundedFrameView * roundedFrame = [TPRoundedFrameView new];
roundedFrame.cornerRadius = 5.f;
roundedFrame.borderColor = [UIColor groupTableViewBackgroundColor];
// add borders to your view with appropriate constraints
[self.myRoundedView addSubview:roundedFrame];
roundedFrame.translatesAutoresizingMaskIntoConstraints = NO;
NSDictionary * views = NSDictionaryOfVariableBindings(roundedFrame);
NSArray * horizontal = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-0-[roundedFrame]-0-|" options:0 metrics:nil views:views];
NSArray * vertical = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-0-[roundedFrame]-0-|" options:0 metrics:nil views:views];
[self.myRoundedView addConstraints:horizontal];
[self.myRoundedView addConstraints:vertical];
}
Result:
Table with rounded views as cells
I fixed all of my performance borderRadius issues by applying this radius on the contentView instead of the cell itself.
self.contentView.layer.borderWidth = 1.0f;
self.contentView.layer.cornerRadius = 5.0f;
self.contentView.layer.borderColor = [UIColor colorWithRed:202/255. green:202/255. blue:202/255. alpha:1.0].CGColor;

Static subview background image effect

In the latest Expedia app for iOS, they have a very interesting effect that I am trying to wrap my head around. The have two columns of infinitely scrolling subviews which I know can be accomplished with 2 scrollviews. The interesting part is that the overall scrollview appears to have a linen background that stays static and can be seen in the gap between each of the subview cells. The really cool part is that the subviews have a different background that stays in place. In the screenshot below it is city skyline image. When the subviews scroll, the city image can only be seen behind the subview cells. It appears to be some sort of masking trick but I can't quite figure out how the effect is done. How can I achieve the same result?
Essentially, how can you show a static background behind subviews that act as little windows and not show the linen. The linen should only be shown around the cells.
You can download the app, hit airplane mode and try it for yourself.
Here is a screenshot:
Here is another to show that the cells scrolled but the city stays the same:
I'd like to found an elegant solution, for now I would do it by tracking the visible subviews offset and configuring their appearance.
Please check the result at sample project.
For the future reference I'll attach the code below:
ViewController.m
//
// OSViewController.m
// ScrollMasks
//
// Created by #%$^Q& on 11/30/12.
// Copyright (c) 2012 Demo. All rights reserved.
//
#import "OSViewController.h"
#interface OSViewController ()
// subviews
#property (strong) IBOutlet UIScrollView * scrollView;
// all the subviews
#property (strong) NSArray * maskedSubviews;
// subviews visible at scrollview, we'll update only them
#property (strong) NSArray * visibleMaskedSubviews;
// updates the views from visibleMaskedSubviews
-(void) updateVisibleSubviews;
// updates the visibleMaskedSubviews array with the given scrollView offset
-(void) updateVisibleSubviewsArrayForOffset:(CGPoint) offset;
#end
#implementation OSViewController
-(void) unused {}
#pragma mark - view
-(void) viewWillAppear:(BOOL)animated {
[self updateVisibleSubviews];
[super viewWillAppear:animated];
}
- (void)viewDidLoad
{
[super viewDidLoad];
/*
See -updateVisibleSubviews comment for the class comments
*/
UIView * newMaskedView = nil;
NSMutableArray * newMaskedSubviews = [NSMutableArray array];
const CGSize scrollViewSize = self.scrollView.bounds.size;
const int totalSubviews = 10;
const float offset = 20.;
const float height = 100.;
UIImage * maskImage = [UIImage imageNamed:#"PeeringFrog.jpg"];
/*
// Uncomment to compare
UIImageView * iv = [[UIImageView alloc] initWithFrame:self.scrollView.bounds];
iv.image = maskImage;
[self.view insertSubview:iv atIndex:0];
*/
// add scrollview subviews
for (int i = 0; i < totalSubviews; i++) {
CGRect newViewFrame = CGRectMake(offset, offset*(i+1) + height*i, scrollViewSize.width - offset*2, height);
newMaskedView = [UIView new];
newMaskedView.frame = newViewFrame;
newMaskedView.clipsToBounds = YES;
newMaskedView.backgroundColor = [UIColor redColor];
newMaskedView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth;
UIImageView * maskImageView = [UIImageView new];
maskImageView.frame = CGRectMake(0, 0, self.scrollView.bounds.size.width, self.scrollView.bounds.size.height);
maskImageView.image = maskImage;
[newMaskedView addSubview:maskImageView];
[self.scrollView addSubview:newMaskedView];
[newMaskedSubviews addObject:newMaskedView];
}
self.scrollView.contentSize = CGSizeMake(scrollViewSize.width, (height+offset)*totalSubviews + offset*2);
self.maskedSubviews = [NSArray arrayWithArray:newMaskedSubviews];
[self updateVisibleSubviewsArrayForOffset:self.scrollView.contentOffset];
}
-(void) updateVisibleSubviews {
[self updateVisibleSubviewsArrayForOffset:self.scrollView.contentOffset];
for (UIView * view in self.visibleMaskedSubviews) {
/*
TODO:
view must be UIView subclass with the imageView initializer and imageView frame update method
*/
CGPoint viewOffset = [self.view convertPoint:CGPointZero fromView:view];
UIImageView * subview = [[view subviews] objectAtIndex:0];
CGRect subviewFrame = subview.frame;
subviewFrame = CGRectMake(-viewOffset.x, -viewOffset.y, subviewFrame.size.width, subviewFrame.size.height);
subview.frame = subviewFrame;
}
}
#pragma mark - scrollview delegate & utilities
-(void) scrollViewDidScroll:(UIScrollView *)scrollView {
[self updateVisibleSubviews];
}
-(void) updateVisibleSubviewsArrayForOffset:(CGPoint) offset {
NSMutableArray * newVisibleMaskedSubviews = [NSMutableArray array];
for (UIView * view in self.maskedSubviews) {
CGRect intersectionRect = CGRectIntersection(view.frame, self.scrollView.bounds);
if (NO == CGRectIsNull(intersectionRect)) {
[newVisibleMaskedSubviews addObject:view];
}
}
self.visibleMaskedSubviews = [NSArray arrayWithArray:newVisibleMaskedSubviews];
}
#pragma mark - memory
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
ViewController.h
//
// OSViewController.h
// ScrollMasks
//
// Created by #%$^Q& on 11/30/12.
// Copyright (c) 2012 Demo. All rights reserved.
//
/*
PeeringFrog image is taken (and resized) from Apple sample project "PhotoScroller"
*/
#import <UIKit/UIKit.h>
#interface OSViewController : UIViewController <UIScrollViewDelegate>
#end
I did something similar a few years ago. At first I tried using the CGImageMaskCreate stuff, but found it far easier just to create an image that had transparent "cutouts" and then used animation effects to scroll the picture(s) under it.
For your case, I'd find an image of linen the size of the screen. Then I'd use a image editor (I use GIMP) to draw some number of boxes on the linen using a flat color. Then I'd map that box color to transparent to make the cutouts. There's other ways to do this, but that's the way I do it.
In your app, add two or more image views to the main view. Don't worry about the placement because that will be determined at run time. You'll want to set these image views to contain the images you want to have "scroll" under. Then add your linen-with-cutouts UIImageView so it's on top and it's occupying the entire screen size. Make sure that the top UIImageView's background is set to transparent.
When the app starts, layout your "underneath" imageviews, top to bottom, and then start a [UIView beginAnimation] that scrolls your underneath images views up by modifying the "y" position. This animation should have a done callback that gets called when the top image view is completely off the screen. Then, in the done callback, layout the current state and start the animation again. Here's the guts of the code I used (but note, my scrolling was right to left, not bottom to top and my images were all the same size.)
- (void)doAnimationSet
{
[iv1 setFrame:CGRectMake(0, 0, imageWidth, imageHeight)];
[iv2 setFrame:CGRectMake(imageWidth, 0, imageWidth, imageHeight)];
[iv3 setFrame:CGRectMake(imageWidth*2, 0, imageWidth, imageHeight)];
[self loadNextImageSet];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:10];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
[iv1 setFrame:CGRectMake(-imageWidth, 0, imageWidth, imageHeight)];
[iv2 setFrame:CGRectMake(0, 0, imageWidth, imageHeight)];
[iv3 setFrame:CGRectMake(imageWidth, 0, imageWidth, imageHeight)];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(doneAnimation:finished:context:)];
[UIView commitAnimations];
}
- (void)doneAnimation:(NSString *)aid finished:(BOOL)fin context:(void *)context
{
[self doAnimationSet];
}
This should give you the effect that you are looking for. Good luck :)

Resources