Looping multiple methods - iphone

I've made a program that generates an image at a random x-coordinate at the top of the screen. The image then falls down to the bottom. However, I want to keep generating new images (of the same image) every few seconds so that it's as though these duplicates of the same image are continually "raining" from the top.
How can I make all of this code repeat every 0.5 seconds?
#implementation ViewController {
UIImageView *_myImage;
}
- (void)viewDidLoad
{
srand(time(NULL));e
int random_x_coordinate = rand() % 286;
CGRect myImageRect = CGRectMake(random_x_coordinate, 0.0f, 40.0f, 40.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage imageNamed:#"flake.png"]];
myImage.opaque = YES;
[self.view addSubview:myImage];
_myImage = myImage;
//FALLING BIRDS TIMER
moveObjectTimer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:#selector(moveObject) userInfo:nil repeats:YES];
}
//FALLING BIRDS MOVER
-(void) moveObject { // + means down and the number next to it is how many pixels y moves down per each tick of the TIMER above
_myImage.center = CGPointMake(_myImage.center.x, _myImage.center.y +1);
}

Just put animation cycle inside the method you call on timer, something like
- (void)viewDidLoad
{
[super viewDidLoad];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5
target:self
selector:#selector(animate)
userInfo:nil repeats:YES];
[timer fire];
}
- (void)animate
{
CGFloat hue = ( arc4random() % 256 / 256.0 ); // 0.0 to 1.0
CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from white
CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from black
UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
view.backgroundColor = color;
[self.view addSubview:view];
[UIView animateWithDuration:1.0 animations:^{
view.frame = CGRectMake(0, 200, 50, 50);
}];
}
Will give you squares dropping down from top, continuously. Just remember to clean up unused views regularly to avoid memory issues.

Related

Contents are shuffles in GridView

I am new to IOS development. I am using custom GridView to load the content in my project, and it is working fine for Simulator when the content reloads. But in iPad the content gets shuffles when reloads.
- (void)reloadData {
if (_gridViewDelegate && self.superview != nil) {
CGFloat maxX = 0.f;
CGFloat maxY = 0.f;
_scrollView.pagingEnabled = YES;
self.gridRects = [self.gridViewDelegate rectsForCellsInGridView:self];
[self.gridCells.allValues makeObjectsPerformSelector:#selector(removeFromSuperview)];
[self.reuseableCells addObjectsFromArray:self.gridCells.allValues];
[self.gridCells removeAllObjects];
for (NSValue *rectValue in self.gridRects) {
CGRect rect = [rectValue CGRectValue];
maxX = MAX(maxX, rect.origin.x + rect.size.width);
maxY = MAX(maxY, rect.origin.y + rect.size.height);
}
CGFloat pageWidth = self.scrollView.frame.size.width;
self.maximumContentWidth=maxX;
maxX = MAX(MIN(maxX, self.maximumContentWidth), self.contentSize.width);
maxY = MAX(MIN(maxX, self.maximumContentHeight), self.contentSize.height);
maxX=pageCount*pageWidth;
self.scrollView.contentSize = CGSizeMake(maxX, maxY);
[self loadCellsInRect:self.visibleRect];
[self updateStickyViewsPosition];
[pageNumberLable removeFromSuperview];
currentPage = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
if(pageWidth == 1024)
{
pageNumberLable=[[UILabel alloc]initWithFrame:CGRectMake(self.scrollView.contentOffset.x+990, 690, 20, 20)];
pageNumberLable.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
}
else
{
pageNumberLable=[[UILabel alloc]initWithFrame:CGRectMake(self.scrollView.contentOffset.x+740, 943, 20, 20)];
pageNumberLable.backgroundColor=[UIColor redColor];
pageNumberLable.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
}
pageNumberLable.text=[NSString stringWithFormat:#"%d",currentPage+1];
pageNumberLable.textColor=[UIColor blackColor];
pageNumberLable.font = [UIFont boldSystemFontOfSize:16];
pageNumberLable.backgroundColor=[UIColor clearColor];
[self.scrollView addSubview:pageNumberLable];
pageIndex = [NSUserDefaults standardUserDefaults];
[pageIndex setInteger:currentPage+1 forKey:#"integerKey"];
}
}
-(void)reloadGrid
{
if(rotate == newIntValue)
{
[spinningLibrary stopAnimating];
[update removeFromSuperview];
settingLabel.hidden=YES;
spinningLibrary.hidden=YES;
}
if(rotate<newIntValue)
{
rotate++;
[self.gridView scrollRectToVisible:CGRectMake(768*rotate, 0, self.gridView.frame.size.width, self.gridView.frame.size.height) animated:YES];
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(reloadGrid123) userInfo:nil repeats:NO];
}
[NSThread sleepForTimeInterval:0.2];
self.gridView.scrollView.hidden=NO;
[settingsPopoverController dismissPopoverAnimated:YES];
}
You're comparing iPad's RAM and your machine's RAM.It's not fair though.
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(reloadGrid123) userInfo:nil repeats:NO];
Try to adjust the interval(> 0.1) by setting, scheduledTimerWithTimeInterval.
And it's a bad way of blocking the main thread.
Use below blocks approach to "do something after sometime".
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do something taking a long time in background.
[NSThread sleepForTimeInterval:0.2];
// Background thread has finished it's work.
// Call another block on main thread to do UI stuff like updating etc..
dispatch_async(dispatch_get_main_queue(), ^{
// Here you are in the main thread again
// You can do whatever you want
});
});

how do I stack the UIImage together and wavering or swing in UIKit

I would like to know how this app stacks up uiimage and wavering in UIKit.
I'm following this xcode: Using a UIImageView subclass with NSTimers
to have images dropping down in random, but how do I catch it and stack the UIImage together ?
Thanks for the reply... EDIT: for clarity
https://www.youtube.com/watch?v=2dpZCoi4xFk 40sec onwards will show how it stack on top each other and swing with accerometer
This will emulate the dropping of UIIimageView
- (void)viewDidLoad {
[super viewDidLoad];
// set the background color to something COLD
self.view.backgroundColor = [UIColor colorWithRed:0.0 green:0.5 blue:1.0 alpha:1.0];
// load our ph image we will use the same image over and over
phImage = [UIImage imageNamed:#"placeholder.png"];
// start a timet that will fire 1 times per second
[NSTimer scheduledTimerWithTimeInterval:(1) target:self selector:#selector(onTimer) userInfo:nil repeats:YES];
}
// Timer event is called whenever the timer fires
- (void)onTimer
{
// build a view from our ph image
UIImageView* placeholderView = [[UIImageView alloc] initWithImage:phImage];
// use the random() function to randomize up our ph attributes
//int startX = round(random() % 300);
int startX = round(random() % 275);
//int endX = round(random() % 300);
int endX = startX;
double scale = 1 / round(random() % 100) + 1.0;
double speed = 1 / round(random() % 50) + 1.0;
// set the PH start position
phView.frame = CGRectMake(startX, -100.0, 25.0 * scale, 25.0 * scale);
phView.alpha = 0.25;
// put the ph in our main view
[self.view addSubview:phView];
[UIView beginAnimations:nil context:phView];
// set up how fast the ph will fall
[UIView setAnimationDuration:5 * speed];
// set the postion where ph will move to
phView.frame = CGRectMake(endX, 500.0, 25.0 * scale, 25.0 * scale);
// set a stop callback so we can cleanup the ph when it reaches the
// end of its animation
[UIView setAnimationDidStopSelector:#selector(onAnimationComplete:finished:context:)];
[UIView setAnimationDelegate:self];
[UIView commitAnimations];
}
- (void)onAnimationComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
UIImageView *phView = context;
[phView removeFromSuperview];
NSLog(#"[phView retainCount] = %d",[phView retainCount]);
}
Thanks for reading and commenting.
For stacking, just make a UIView that holds all the placed images together.
UIView *stackView = [UIView new];
-(void) addView: (UIView*) view toStack: (UIView*) stackView
{
if ([stackView subviews].count > 0)
{
CGRect frame = [[[stackView subviews] lastObject] frame];
view.frame = CGRectOffset(frame, 0, 20);
}
[stackView addSubview:view];
}
For tilting, set up an accelerometer and use the x and y to determine the tilt.
-(void)configureAccelerometer
{
UIAccelerometer* theAccelerometer = [UIAccelerometer sharedAccelerometer];
theAccelerometer.updateInterval = 0.20;
theAccelerometer.delegate = self;
// Delegate events begin immediately.
}
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
UIAccelerationValue x, y, z;
x = acceleration.x;
y = acceleration.y;
//[stackView tiltForX: x Y: y]
}
More info on Motion Events
For the collision detection, you can probably do something like
if (CGRectIntersectsRect([[[stackView subviews] lastObject] frame], fallingView.frame))
[self addView: fallingView toStack: stackView];

Marquee effect in uiimageview iPhone

How can I implement marquee effect animation in UIImage.
I have a image of cloud (320*480). I need to animation it continuously left from right without any lagging and disappearing. Below is a sample of html.
http://www.quackit.com/html/codes/html_marquee_code.cfm
2nd from top(Continuous scrolling text:).
Please help
UIImage *clouds = [UIImage imageNamed:#"Clouds"];
UIImageView *cloudView = [[UIImageView alloc] initWithImage:clouds];
CGRect origin = CGRectMake(320, 0, clouds.size.width, clouds.size.height);
CGRect destination = CGRectMake(0, 0, clouds.size.width, clouds.size.height);
cloudView.frame = origin;
[self.view addSubview:cloudView];
[UIView animateWithDuration:5 delay:0 options:UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveLinear animations:^{
cloudView.frame = destination;
} completion:nil];
Do this:
-(void)marqueeEffect
{
imgView.frame = CGRectMake(self.view.frame.origin.y,50,320,480); //right frame
//increase time duration as per requirement
[UIView animateWithDuration:3.0
delay: 0.0
options: UIViewAnimationCurveEaseOut
animations:^{
imgView.frame = CGRectMake(-imgview.frame.size.width,50,320,480); //left frame
}
completion:^(BOOL finished){
[self performSelector:#selector(marqueeEffect)];
}];
}
TRY THIS EXAMPLE , ITS FOR UILABEL:
int x;
#synthesize label;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
label=[[UILabel alloc]initWithFrame:CGRectMake(300, 400, 150, 30)];
label.text=#"WWW.SONGS.PK";
label.backgroundColor=[UIColor clearColor];
x=300;
[NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:#selector(clickme) userInfo:nil repeats:YES];
}
-(void)clickme
{
x--;
label.frame=CGRectMake(x, 400, 150, 30);
if( x==-150)
{
x=300;
}
[self.view addSubview:label];
}

Move 10 images continuously in the time interval of 5 sec using objective c?

I have some 10 images, I wanted to show 10 images continuously in two way, one by moving the image with user interaction and other way by automatically moving the images in a time interval with out any user interaction. Following code allow me to move images when user touch and moves the image.... but how can i move the images automatically?
{
scrollView.delegate = self;
[self.scrollView setBackgroundColor:[UIColor blackColor]];
[scrollView setCanCancelContentTouches:NO];
scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView.clipsToBounds = YES;
scrollView.scrollEnabled = YES;
scrollView.pagingEnabled = YES;
NSUInteger nimages = 0;
CGFloat cx = 0;
for (; ; nimages++) {
NSString *imageName = [NSString stringWithFormat:#"pimac%d.gif", (nimages + 1)];
UIImage *image = [UIImage imageNamed:imageName];
if (image == nil) {
break;
}
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
CGRect rect = imageView.frame;
rect.size.height = image.size.height;
rect.size.width = image.size.width;
rect.origin.x = ((scrollView.frame.size.width - image.size.width) / 2) + cx;
rect.origin.y = ((scrollView.frame.size.height - image.size.height) / 2);
imageView.frame = rect;
[scrollView addSubview:imageView];
[imageView release];
cx += scrollView.frame.size.width;
}
self.pageControl.numberOfPages = nimages;
[scrollView setContentSize:CGSizeMake(cx, [scrollView bounds].size.height)];
}
You can use NSTimmer and invoke your image move function there.
self.timer = [NSTimer scheduledTimerWithTimeInterval:5
target:self
selector:#selector(imageMove)
userInfo:nil
repeats:YES];
const CGFloat kScrollObjWidth = 320.0;
const NSUInteger kNumImages = 3;
-(void)viewdidLoad
{
// additional further step
[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(onTimer) userInfo:nil repeats:YES];
curXLoc=0;
}
- (void) onTimer {
curXLoc += kScrollObjWidth;
//This makes the scrollView scroll to the desired position
if(curXLoc<(kNumImages * kScrollObjWidth))
ScrollView.contentOffset = CGPointMake(curXLoc,0 );
else
{
curXLoc =0;
ScrollView.contentOffset = CGPointMake(curXLoc,0 );
}
}

UIView opacity gradient

Is it possible to have a UIIView with a textured background image and an opacity gradient? i.e., the bg image should fade in from left to right against the background container view.
thanks
Save your background image with an alpha channel (i.e. PNG) and do the fade in whatever graphics app you use.
Then, put it as the first child of your UIView as a UIImageView
- (void)viewDidLoad {
[super viewDidLoad];
image1=[[UIImageView alloc]initWithImage:[UIImage imageNamed:#"Default.png"]];
image1.frame=CGRectMake(0, 0, 320, 460);
image2=[[UIImageView alloc]initWithImage:[UIImage imageNamed:#"directoryPage.png"]];
image2.frame=CGRectMake(0, 0, 320, 480);
[self.navigationController setNavigationBarHidden:YES];
}
- (void)fade
{
image2.alpha = 0;
[self.view addSubview:image2];
// The upper layer will transition from alpha 1 to 0s
[self.view addSubview:image1];
BSheepAppDelegate *appD=(BSheepAppDelegate *)[[UIApplication sharedApplication]delegate];
if(appD.flag==0){
timer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:#selector(fadeTimerEvent) userInfo:nil repeats:YES];
appD.flag=1;
}
else if (appD.flag==1) {
[self.view addSubview:image2];
image2.alpha=1;
}
}
// Rate of transition for alpha values
#define FADE_IN_RATE 1.0/100.0
#define FADE_OUT_RATE 2.0/200.0
- (void)fadeTimerEvent
{
if (image2.alpha >= 1)
{
// At this point, image2 is now visible
[timer invalidate];
timer = nil;
}
else
{
// Fade lower layer in (increase alpha)
image2.alpha += FADE_IN_RATE;
// Fade upper layer out (decrease alpha)
image1.alpha -= FADE_OUT_RATE;
}
}
use this code to set