Iphone app - How to show the digital clock with current time - iphone

Hello all I am working an iphone app where I need to show the current time in a watch That is there is a watch which displays the static time or static image . Then we need to find the current time then move all the hrs,mins ,seconds pins such tht they should set to their time.
Do u have any ideas to do this
Thanks Everyone
Here is my code:
//Calculate angles:
float minutesAngle = (0/60)*360;
float hoursAngle = (10/12)*360;
//Begin the animation block
[UIView beginAnimations:#"moveHands" context:nil];
[UIView setAnimationDuration:0.5];
minsImageView.transform = CGAffineTransformRotate(minsImageView.transform, minutesAngle);
hoursImageView.transform = CGAffineTransformRotate(hoursImageView.transform, hoursAngle);
[UIView commitAnimations];
where as minsImageView ,hoursImageView are the imageViews set in the XIB who shows the static image
But its not effecting at all..

Once you have individual time values (it sounds like you've figured this out already) you can position your hands as needed.
This means it's time to brush up on your math skills. I think this'll give you a start:
A circle has 360 degrees in it. This means that for whatever time unit we get, we divide by the maximum value of that time unit to get a fraction and multiply the result by 360 (instead of 100 like a percentage) to get our number of degrees.
So, if we had 23 seconds:
23/60 = 3.83333.8333 x 360 = 138 degrees
Now we know how many degrees to rotate our object. I would get a designer to make you some nice hand images and put them in UIImageViews. Then, you can rotate them around their origins like so:
secondHandImage.transform = CGAffineTransformMakeRotate(secondAngle);
Good luck :)
EDIT: Let's assume that our hands are on 10:10. If we wanted to move them to 01:00 we would do something like the following. Tweak it as needed.
//Calculate angles:
float minutesAngle = (0/60)*360;
float hoursAngle = (10/12)*360;
//Begin the animation block
[UIView beginAnimations:#"moveHands" context:nil];
[UIView setAnimationDuration:0.5];
minutesHand.transform = CGAffineTransformRotate(minutesHand.transform, minutesAngle);
hoursHand.transform = CGAffineTransformRotate(hoursHand.transform, hoursAngle);
[UIView commitAnimations];

If you're trying to show a digital clock, your life is SOOOO much easier than my previous answer related to analog clocks.
Create images with the numbers 0-9 and put them in your bundle. Have four UIImageViews in your UI in this configuration:
[][]:[][]
[ ] = UIImageVIew
Then, you can simply change the images in each slot to reflect the time. If you use transparent backgrounds and high resolution graphics, you can create really convincing effects.

Related

move image on tilt within boundaries

I'm currently creating a iPhone app that displays my speed heading location and a few other sensor readings for use on my bike. I've managed to get the tilt reading from the accelerator. what I'm trying to do is move an image either left or right depending on what the tilt reading is.
_______________________________
: === :
: = = :
: === :
-------------------------------
lets say the = signs is my image, I'm trying to get it to move either towards the left or right edge depending on the tilt angle.
any ideas? I've managed to move it by animations but I don't want it to continuously move if I'm leaning for a long period of time.
First I added the accelerator data using:
UIAccelerometer *theAccelerometer = [UIAccelerometer sharedAccelerometer];
theAccelerometer.updateInterval = 0.1; //in seconds
theAccelerometer.delegate = self;
Notice the timing is 0.1 seconds. You will want to match that timing to the animation below. I then set the animation up in the accelerometer:didAccelerate: delegate call:
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
NSInteger newX = 0;
newX = imageView.frame.size.width/2 + ((320-imageView.frame.size.width) * (acceleration.x+1)/2.0);
[UIView animateWithDuration:0.1 animations:^{
imageView.center = CGPointMake(newX, imageView.center.y);
}] ;
}
It is important to match the animation duration with the updateInterval of the UIAccelerometer so that you make sure to complete the animation before the next update comes through.
The important part here is probably the math to determine the newX position. I basically took half of the width of the image, because that is the left most absolute position. From there I knew I had a 320-imageView.frame.size.width amount of room that I could add. If I added the entire 320-imageView.frame.size.width then I would be at 320-imageView.frame.size.width/2 which is the right-most position. From there I just needed to break up the 320-imageView.frame.size.width chunk according to how much we have accelerated. The accelerator.x data is in the range -1 to 1, so my entire range is 2. So I added 1 to the accelerator.x to normalize it from 0-2. Then I divided by 2.0 so that I would have a range from 0-1. Now I had a multiplier that I could multiply my 320-imageView.frame.size.width range by. If it was 0 I would be at the left-most position. If it was 1 I would be at the right-most position, and anything in between would be broken up linearly. So the final term is:
imageView.frame.size.width/2 + ((320-imageView.frame.size.width) * (acceleration.x+1)/2.0);
to get the new x position of the image.
I hope that is what you are looking for! I tested it on a device and it is pretty smooth as long as you match up your durations.
If you are asking the question about animation. This is code apple recommnad to animate UIView. And you can change value for x and y coordinate.
imageFrame.origin.y = 200;
[UIView animateWithDuration:0.5
delay:0.0
options: UIViewAnimationCurveEaseOut
animations:^{
datePickerView.frame = imageFrame;
}
completion:^(BOOL finished){
self.datePickerViewFlag = YES;
}];

problem with collision of two images

Well here is my problem:
I have two images : flakeImage and ViewToRotate. What I want is that if flakeImage touches ViewToRotate, ViewToRotate.alpha=0.5; but when FlakeImage appears on the screen ViewToRotate.alpha=0.5; without touching it. I think it's a problem with my view beacause I have :
UIImageView* flakeView = [[UIImageView alloc] initWithImage:flakeImage];
here is the code :
UIImageView* flakeView = [[UIImageView alloc] initWithImage:flakeImage];
// use the random() function to randomize up our flake attributes
int startY = round(random() % 320);
// set the flake start position
flakeView.center = CGPointMake(490, startY);
flakeView.alpha = 1;
// put the flake in our main view
[self.view addSubview:flakeView];
[UIView beginAnimations:nil context:flakeView];
// set up how fast the flake will fall
[UIView setAnimationDuration:7 ];
// set the postion where flake will move to
flakeView.center = viewToRotate.center;
// set a stop callback so we can cleanup the flake when it reaches the
// end of its animation
[UIView setAnimationDelegate:self];
[UIView commitAnimations];
How can I solve this please ?
if someone could help me it would be very cool.
I have a bit of sophomoric experience with this, having written http://itunes.apple.com/us/app/balls/id372269039?mt=8. If you check that app out, you will see a bit of the same problem. This topic is a pretty deep rabbit hole. WHen I started that app, I didn't even know how to write a decent game loop. You will need that first because you need to do precise time-step calculations. AFA the collisions, you update your model and view separately, so if you update the model and objects overlap, you need to back them up until they don't collide and then update your view with the result. If you plan to have a lot of colliding objects, you may hit a wall using UIViews. To complicate things more, if your objects are round, CGRectIntersectsRect won't exactly work. That complicates the math a bit, but it's not too bad. With my app, I found it quite difficult to get the physics to look realistic. THe problem became that ball A and B overlap, so you back them up, then they now intersect other balls, etc, etc. This link is a good starting point, but there are quite a few examples of code out there that "almost" work.
CGRect has a intersection function. The frames of UIViews are CGRects.
if (CGRectIntersectsRect(view1.frame, view2.frame) == 1)
NSLog(#"The views intersect");
else
NSLog(#"The views do not intersect");
The problem I foresee is that if the rects have lots of whitespace, they will appear to intersect before they actually touch
Secondly, you should switch up to block animations. It's strongly encouraged
UIImageView* flakeView = [[[UIImageView alloc] initWithImage:flakeImage] autorelease];
// use the random() function to randomize up our flake attributes
int startY = round(random() % 320);
// set the flake start position
flakeView.center = CGPointMake(490, startY);
flakeView.alpha = 1;
// put the flake in our main view
[self.view addSubview:flakeView];
[UIView animateWithDuration:.7
animations:^ {
// set the postion where flake will move to
flakeView.center = viewToRotate.center;
};
Did this all from memory, no idea if there are errors.
Circular Collision:
a^2 + b^2 < c^2 means they collide
if(pow(view2.frame.origin.x - view1.frame.origin.x, 2) +
pow(view2.frame.origin.y - view1.frame.origin.y, 2) <
pow(view1.frame.size.width/2, 2))
{
//collision
}
else
{
//no collision
}
Again, all from memory, check for errors on your own

smooth animation in iOS using CoreAnimation

CoreAnimation is a pretty easy thing, but:
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:30];
MyImageView.frame = CGRectOffset(MyImageView.frame, 100, 0);
[UIView commitAnimations];
I want to move the ImageView by 100 Pixel veeeery slowly. Therefore all positioning values are double I expect the Layoutsystem to position the items with subpixel accuracy.
Butt when I watch this animation i see the ImageView "jumping" pixelwise instead of a smooth traveling.
Any ideas to come to a real subpixelpositioning?
I also tried to set the position with a timer and recalculate the frame-values, but same effect.
Update:
In an other part of my App I use the Accelerometer to update the position of a ImageView, and do basicly calculate the position ad size of the graphic an then do:
MyImageView.frame = newCGRect;
I get around 60 Updates/s from the Accelerometer and added the LowPass-Filter from the Accelerometer example from Apple.
Here the positioning is perfect?!?!
Why does this do not happen with CoreAnimation?
Thanks for any help.
Try using CGAffineTransformTranslate(MyImageView.transform, 100, 0) instead of CGRectOffset.
Reference here:
http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/CGAffineTransform/Reference/reference.html
If you use CABasicAnimation in QuartzCore framework, you can smoothen your animation using "CAMediaTimingFunction". Built-in alternatives worked for me but as far as I know you can define your own timing functions as well.
CABasicAnimation *starShineAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation"];
starShineAnimation.removedOnCompletion = NO;
starShineAnimation.fillMode = kCAFillModeForwards;
starShineAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
....

Developing A Simple Game without using Game Engines?

I am trying to develop a simple soccer game including penalty kicks in which i have to animate a ball from player to the goal post...earlier i have been using simple animations using a timer to add to the axis of ball image so that it moves from 1 point to another..but i did not have the desired result as animations were not that smooth...So i was thinking of using a Game Engine...Since i am a New Programmer i have no idea about game engine and neither can i find any proper documentation regarding engines like box2d or chipmunks or sparrow..i was also thinking of using UIView animations instead of the earlier animations as i think that can achieve far better animations without scratching my head trying to work on a game engine....I am going no where with this so it would be really great if someone can put some light on this issue of mine???
Use UIView animations, like in:
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3]; // or whatever time
object.center=CGPointMake(object.center.x+2, object.center.y+4);
// or whatever
[UIView commitAnimations];
You should also use an NSTimer with the same interval so that you can call animations smoothly.
NSTimer *timer=[NSTimer scheduledTimerWithTimeInterval:0.3 target: self
selector:#selector(animation) userInfo: nil repeats: YES];
Then, implement the method:
- (void)animation {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3]; // or whatever time
object.center=CGPointMake(object.center.x+5, object.center.y+7);
// or whatever
[UIView commitAnimations];
}
This should do for ANY simple game.
As you tagged the question with cocos2d, I guess you're using it, or planning to. Animating CCSprites is easy as you can see e.g. in this game https://github.com/haqu/tweejump.
In your onEnter implementation, just call
[self scheduleUpdate]
this will call routinely the update: where you can do your drawing
- (void)update:(ccTime)dt {
ball_pos.x += ball_velocity.x * dt;
ball_pos.y += ball_velocity.y * dt;
ball_velocity.x += ball_acc.x * dt;
ball_velocity.y += ball_acc.y * dt;
//game logic goes here (collision, goal, ...)
ball.position = ball_position;
}
That'll handle smooth movement of the ball. ball_pos, ball_velocity and ball_acc being vvCertex2F.
You probably don't even have to deal with acceleration, and only give an impulse to the ball when someone hit it (i.e. bump the velocity).
You probably also want some damping to slow the ball down. you do it by reducing the velocity at every step

Can i move the origin when doing a rotation transform in Quartz 2D for the iPhone?

Sorry if this is obvious or covered elsewhere, but i've been googling all day and haven't found a solution that actually worked.
My problem is as follows: I am currently drawing an image in a full screen UIView, for examples sake we'll say the image is in the bottom right corner of the UIView. I'd like to do a rotation transform(CGAffineTransformMakeRotation) at the center of that image, however, by default the rotation command rotates around the center of the UIView it self. As a result, my image moves around the screen when i rotate instead of it staying in place and rotating around its own center.
From what i've gathered, i need to translate my context so that the origin(center of the UIView) is at the center of my image, Rotate, and then restore the context by translating back to the original spot.
The following is the closest thing i've gotten to work, but the problem is that while the image is rotating, it moves downward while it's rotating. I think this is caused by animation tweening the 1st step translate and 3rd step translate instead of just realizing that the beginning and end point on the translates would be the same...
// Before this i'd make a call to a function that draws a path to a passed in context
CGAffineTransform inverseTranslation = CGAffineTransformMakeTranslation( transX, transY );
CGAffineTransform translation = CGAffineTransformMakeTranslation( -transX, -transY );
CGAffineTransform rot = CGAffineTransformMakeRotation( 3.14 );
CGAffineTransform final = CGAffineTransformConcat( CGAffineTransformConcat( inverseTranslation, rot ), translation );
// Then i apply the transformation animation like normal using self.transform = final etc etc
I've also tried stuff like CGContextTranslateCTM and CGContextSaveGState/UIGraphicsPushContext, but these seem to have little effect.
I've been fighting with this for days and my current solution seems close, but i have no clue how to get rid of that translating tweening. Does anyone have a solution for this or a better way to go about this?
[update]
For the time being i'm drawing my image centered at the UIview's center and then setting the UIView.center property to the origin i'd like to rotate and then doing the rotate command. Seems like a bit of a hack, but until i can get the real translates working it's my only choice.
Thanks!
duncanwilcox' answer is the right one, but he left out the part where you change the anchor of the view's layer to the point you want to rotate around.
CGSize sz = theview.bounds.size;
// Anchorpoint coords are between 0.0 and 1.0
theview.layer.anchorPoint = CGPointMake(rotPoint.x/sz.width, rotPoint.y/sz.height);
[UIView beginAnimations:#"rotate" context:nil];
theview.transform = CGAffineTransformMakeRotation( 45. / 180. * M_PI );
[UIView commitAnimations];
This is documented here: http://developer.apple.com/documentation/Cocoa/Conceptual/CoreAnimation_guide/Articles/Layers.html
This is also an option: a simple change of basis ;-)
CGAffineTransform transform = CGAffineTransformMakeTranslation(x, y);
transform = CGAffineTransformRotate(transform, angle);
transform = CGAffineTransformTranslate(transform,-x,-y);
where (x,y) is the rotation center you like
Rotation happens around the anchorPoint of the view's layer. The default for the anchorPoint is the center (0.5, 0.5), so the rotation alone without the translations should suffice.
Did a quick test and this works for me:
[UIView beginAnimations:#"rotate" context:nil];
self.transform = CGAffineTransformMakeRotation( 45. / 180. * 3.14 );
[UIView commitAnimations];
If you don't want an animation to occur, but just set the new rotation, you can use this:
CGFloat newRotation = 3.14f
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.0]; // no tweening
CGAffineTransform transform = CGAffineTransformMakeRotation(newRotation);
self.transform = transform;
[UIView commitAnimations];
The rotation should indeed take place around the center of the UIView. Setting the animationDuration to zero garantees no tweening should happen.
Be sure though you don't do this 60 times a second. It's very tempting to create game like animations with these tools. These kind of animations aren't exactly meant for a frame to frame based, "lots of sprites flying everywhere" game.
For that - and I've been down that road - the only way to go, is OpenGL.