Pages

Subscribe:

Tuesday, July 19, 2011

How to make a slider button just like iPhone's native Unlock Button


/* In the above screen shot, i've used the UISlider as a alarm triggering object. (as required in an application) */

/* Use your custom images as your requirements. Declare required variables & objects in *.h file. You will need a UIImageView, a UILabel, a UIButton & a UISlider in your NIB file and locate them to desired name.*/

- (void)viewDidLoad {
[super viewDidLoad];
// initialize custom UISlider (you have to do this in viewdidload or applicationdidfinishlaunching.
UIImage *stetchLeftTrack= [[UIImage imageNamed:@"Nothing.png"]
stretchableImageWithLeftCapWidth:30.0 topCapHeight:0.0];
UIImage *stetchRightTrack= [[UIImage imageNamed:@"Nothing.png"]
stretchableImageWithLeftCapWidth:30.0 topCapHeight:0.0];
[mySlider setThumbImage: [UIImage imageNamed:@"SlideToStop.png"] forState:UIControlStateNormal];
[mySlider setMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal];
[mySlider setMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal];

}


-(IBAction)LockIt
{
mySlider.hidden = NO;
lockButton.hidden = YES;
Container.hidden = NO;
myLabel.hidden = NO;
myLabel.alpha = 1.0;
UNLOCKED = NO;
mySlider.value = 0.0;
NSString *str = @"The iPhone is Locked!";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Locked" message:str delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alert show];
[alert release];
}

-(IBAction)fadeLabel
{
myLabel.alpha = 1.0 - mySlider.value;
}

-(IBAction)UnLockIt
{
if (!UNLOCKED)
{
if (mySlider.value == 1.0)
{ // if user slide far enough, stop the operation
// Put here what happens when it is unlocked

mySlider.hidden = YES;
lockButton.hidden = NO;
Container.hidden = YES;
myLabel.hidden = YES;
UNLOCKED = YES;
}
else
{
// user did not slide far enough, so return back to 0 position
[UIView beginAnimations: @"SlideCanceled" context: nil];
[UIView setAnimationDelegate: self];
[UIView setAnimationDuration: 0.35];
// use CurveEaseOut to create "spring" effect
[UIView setAnimationCurve: UIViewAnimationCurveEaseOut];
mySlider.value = 0.0;
[UIView commitAnimations];

/* if u don't want to use custom animation with desired duration then u can use the following line :

[mySlider setValue:0.0 animated:YES];
*/

}
}
}

Friday, July 15, 2011

Accessing & playing iPod's music player through application

- (void)viewDidLoad {
[super viewDidLoad];

mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeAny];
mediaPicker.delegate = self;
mediaPicker.allowsPickingMultipleItems = YES;
mediaPicker.editing = YES;

[self musicPlayerInitialize];

}

-(void)musicPlayerInitialize
{
myPlayer = [MPMusicPlayerController iPodMusicPlayer];

[myPlayer setQueueWithQuery: [MPMediaQuery songsQuery]];
[myPlayer setRepeatMode:MPMusicRepeatModeAll];

[myPlayer beginGeneratingPlaybackNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(changeTitle)
name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object:myPlayer];

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleExternalVolumeChanged:)
name:MPMusicPlayerControllerVolumeDidChangeNotification
object:myPlayer];


}


-(void)changeTitle
{
MPMediaItem *item = [myPlayer nowPlayingItem];
NSString *titleStr = [item valueForProperty:MPMediaItemPropertyTitle];
lblSongTitle.text = titleStr;
NSLog(@"Now Playing Song Name: %@",titleStr);
}


-(IBAction)playButtonPressed
{
if(myPlayer.playbackState == MPMusicPlaybackStatePaused || myPlayer.playbackState == MPMusicPlaybackStateStopped)
{
[myPlayer play];
[btnMusicPlay setImage:[UIImage imageNamed:@"pause_btn.png"] forState:UIControlStateNormal];
}
else if(myPlayer.playbackState == MPMusicPlaybackStatePlaying)
{
[myPlayer pause];
[btnMusicPlay setImage:[UIImage imageNamed:@"play_btn.png"] forState:UIControlStateNormal];
}
[self changeTitle];
}

-(IBAction)nextButtonPressed
{
[myPlayer skipToNextItem];
[self changeTitle];
}

-(IBAction)prevButtonPressed
{
[myPlayer skipToPreviousItem];
[self changeTitle];
}

-(IBAction)volumeChange:(id)sender
{
[[NSUserDefaults standardUserDefaults] setFloat:myVolumeSlider.value forKey:@"musicVolume"];
myPlayer.volume = myVolumeSlider.value;
NSLog(@"volume changing: %f",myVolumeSlider.value);
}

- (void)handleExternalVolumeChanged:(id)notification {
// self.volumeSlider is a UISlider used to display music volume.
// self.musicPlayer.volume ranges from 0.0 to 1.0.
[myVolumeSlider setValue:myPlayer.volume animated:YES];
}


# pragma mark -
# pragma mark media picker Delegate

-(void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker
{
[self dismissModalViewControllerAnimated:YES];
}

-(void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray addObject:mediaItemCollection];

MPMediaItemCollection *tempMediaItem = [tempArray objectAtIndex:0];
[appDelegate.myPlayer setQueueWithItemCollection:tempMediaItem];
[appDelegate.myPlayer play];
[self dismissModalViewControllerAnimated:YES];
}

-(IBAction)playlistButtonPressed
{
[self presentModalViewController:mediaPicker animated:YES];
}

Countdown Timer with remaining time & custom label (hr:min:sec)

-(IBAction)timerStartButtonPressed
{
if(!isStarted)
{
isStarted = TRUE;
isPaused = FALSE;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFunction:) userInfo:nil repeats:YES];
}
}

-(IBAction)timerPauseButtonPressed
{
if(!isPaused)
{
isStarted = FALSE;
isPaused = TRUE;
[timer invalidate];
}
}



-(void)timerFunction:(NSTimer *)theTimer
{
second = second-1;
remSecond = remSecond + 1;

if(hour >= 0)
{
if (second < 0)
minute = minute-1;

if(remSecond > 59)
remMinute = remMinute + 1;

if(minute < 0)
hour = hour - 1;

if(remMinute > 59)
remHour = remHour + 1;

if(minute < 0 && second < 0 && hour < 0)
{
strSecond = @"00";
strMinute = @"00";
strHour = @"00";

NSString *tempTestDuration = [[NSUserDefaults standardUserDefaults] valueForKey:@"restDuration"];
NSArray *tempArray = [tempTestDuration componentsSeparatedByString:@":"];

remHour = [[tempArray objectAtIndex:0] intValue];
remMinute = [[tempArray objectAtIndex:1] intValue];
remSecond = [[tempArray objectAtIndex:2] intValue];


isStarted = FALSE;
isPaused = TRUE;

[timer invalidate];
timer = nil;

if(isTestRunning && remainingSet < totalSet)
{
[self resetRest];
[self timerStartButtonPressed];
}
else if(!isTestRunning && remainingSet < totalSet)
{
[self resetTest];
if([[NSUserDefaults standardUserDefaults] boolForKey:@"isNewSongInEachTestOn"] == YES)
[appDelegate.myPlayer skipToNextItem];
[self timerStartButtonPressed];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Finish!!!" message:@"Time up." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}

return;
}

if (second>=0)
{
if (second<10)
strSecond = [NSString stringWithFormat:@"0%d", second];
else
strSecond = [NSString stringWithFormat:@"%d", second];
}
else
{
second=59;
strSecond = [NSString stringWithFormat:@"%d", second];
}

if(remSecond <= 59)
{
if (remSecond<10)
strRemSecond = [NSString stringWithFormat:@"0%d", remSecond];
else
strRemSecond = [NSString stringWithFormat:@"%d", remSecond];
}
else
{
remSecond=0;
strRemSecond = [NSString stringWithFormat:@"0%d", remSecond];
}

if(minute >= 0)
{
if (minute<10)
strMinute = [NSString stringWithFormat:@"0%d", minute];
else
strMinute = [NSString stringWithFormat:@"%d", minute];
}
else
{
minute = 59;
strMinute = [NSString stringWithFormat:@"%d",minute];
}

if(remMinute <= 59)
{
if (remMinute<10)
strRemMinute = [NSString stringWithFormat:@"0%d", remMinute];
else
strRemMinute = [NSString stringWithFormat:@"%d", remMinute];
}
else
{
minute = 0;
strMinute = [NSString stringWithFormat:@"0%d",remMinute];
}


if (hour<10)
strHour = [NSString stringWithFormat:@"0%d", hour];
else
strHour= [NSString stringWithFormat:@"%d", hour];

if (remHour<10)
strRemHour = [NSString stringWithFormat:@"0%d", remHour];
else
strRemHour= [NSString stringWithFormat:@"%d", remHour];

NSString *tempStr = [NSString stringWithFormat:@"%@:%@:%@",strHour,strMinute,strSecond];
NSString *tempStrRem = [NSString stringWithFormat:@"%@:%@:%@",strRemHour,strRemMinute,strRemSecond];
NSLog(@"tempStr: %@",tempStr);

if([tempStr characterAtIndex:0] == '0')
{
strHour = [NSString stringWithFormat:@"%c",[tempStr characterAtIndex:1]];
tempStr = [NSString stringWithFormat:@"%@:%@:%@",strHour,strMinute,strSecond];
NSLog(@"tempStr: %@",tempStr);

if([tempStr characterAtIndex:0] == '0')
{
tempStr = [NSString stringWithFormat:@"%@:%@",strMinute,strSecond];
NSLog(@"tempStr: %@",tempStr);

if([tempStr characterAtIndex:0] == '0')
{
strMinute = [NSString stringWithFormat:@"%c",[tempStr characterAtIndex:1]];
tempStr = [NSString stringWithFormat:@"%@:%@",strMinute,strSecond];
NSLog(@"tempStr: %@",tempStr);

if([tempStr characterAtIndex:0] == '0')
{
tempStr = [NSString stringWithFormat:@"0:%@",strSecond];
NSLog(@"tempStr: %@",tempStr);
}
}
}
}

if([tempStrRem characterAtIndex:0] == '0')
{
strRemHour = [NSString stringWithFormat:@"%c",[tempStrRem characterAtIndex:1]];
tempStrRem = [NSString stringWithFormat:@"%@:%@:%@",strRemHour,strRemMinute,strRemSecond];
NSLog(@"tempStr: %@",tempStrRem);

if([tempStrRem characterAtIndex:0] == '0')
{
tempStrRem = [NSString stringWithFormat:@"%@:%@",strRemMinute,strRemSecond];
NSLog(@"tempStr: %@",tempStrRem);

if([tempStrRem characterAtIndex:0] == '0')
{
strRemMinute = [NSString stringWithFormat:@"%c",[tempStrRem characterAtIndex:1]];
tempStrRem = [NSString stringWithFormat:@"%@:%@",strRemMinute,strRemSecond];
NSLog(@"tempStr: %@",tempStrRem);

if([tempStrRem characterAtIndex:0] == '0')
{
tempStrRem = [NSString stringWithFormat:@"0:%@",strRemSecond];
NSLog(@"tempStr: %@",tempStrRem);
}
}
}
}


lblTimerDisplay.text = tempStr;
lblRemainingTimeDisplay.text = [NSString stringWithFormat:@"Elapsed Time %@",tempStrRem];
}
else
{
strSecond = @"00";
strMinute = @"00";
strHour = @"00";

[timer invalidate];
}

}

Tuesday, February 8, 2011

Using image & text together or custom view in a UIPickerView

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {

UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
customButton.frame=CGRectMake(5,5, 50, 50);
UIImage *anImage=[UIImage imageNamed:yourImage];
[customButton setImage:anImage forState:UIControlStateNormal];

UILabel *lblTemp = [[UILabel alloc] initWithFrame:CGRectMake(60, 5, 400, 50)];
lblTemp.text = [NSString stringWithFormat:yourText];

UIView *tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 460, 60)];
[tempView addSubview:lblTemp];
[tempView addSubview:customButton];
[view addSubview:tempView];

[lblTemp release];
[tempView release];

return tempView;
}

Wednesday, February 2, 2011

Scaling & Rotating UIImageView through 2 finger swipe

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

NSArray *allTouches = [touches allObjects];

UITouch* t;
if([[event allTouches] count]==1){
if (CGRectContainsPoint([smallImage frame], [[allTouches objectAtIndex:0] locationInView:self.view])) {
t=[[[event allTouches] allObjects] objectAtIndex:0];
touch1=[t locationInView:nil];
}
}else{
t=[[[event allTouches] allObjects] objectAtIndex:0];
touch1=[t locationInView:nil];
t=[[[event allTouches] allObjects] objectAtIndex:1];
touch2=[t locationInView:nil];
}
}


- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

CGPoint currentTouch1;
CGPoint currentTouch2;
NSArray *allTouches = [touches allObjects];
UITouch* t;
float scale,rotation;

if([[event allTouches] count]==1){
t=[[[event allTouches] allObjects] objectAtIndex:0];
if (CGRectContainsPoint([smallImage frame], [[allTouches objectAtIndex:0] locationInView:self.view]))
{
touch2=[t locationInView:nil];
smallImage.center=CGPointMake(smallImage.center.x+touch2.x-touch1.x,smallImage.center.y+touch2.y-touch1.y);
touch1=touch2;
}
}
else if([[event allTouches] count]==2)
{
t=[[[event allTouches] allObjects] objectAtIndex:0];
currentTouch1=[t locationInView:nil];

t=[[[event allTouches] allObjects] objectAtIndex:1];
currentTouch2=[t locationInView:nil];


scale = [self distance:currentTouch1 toPoint:currentTouch2] / [self distance:touch1 toPoint:touch2];
rotation=atan2(currentTouch2.y-currentTouch1.y, currentTouch2.x-currentTouch1.x)-atan2(touch2.y-touch1.y,touch2.x-touch1.x);
if(isnan(scale)){
scale=1.0f;
}
NSLog(@"rotation %f",rotation);

NSLog(@"scale %f",scale);

if (CGRectContainsPoint([smallImage frame], [[allTouches objectAtIndex:0] locationInView:self.view]) &&
CGRectContainsPoint([smallImage frame], [[allTouches objectAtIndex:1] locationInView:self.view]))
{

smallImage.transform=CGAffineTransformScale(smallImage.transform, scale,scale);
smallImage.transform=CGAffineTransformRotate(smallImage.transform, rotation);
}
else // In case of scaling or rotating the background imageView
{
imageView.transform=CGAffineTransformScale(imageView.transform, scale,scale);
imageView.transform=CGAffineTransformRotate(imageView.transform, rotation);
}

touch1=currentTouch1;
touch2=currentTouch2;
}
}

-(double)distance:(CGPoint)point1 toPoint:(CGPoint)point2
{
return sqrt(fabs(point1.x - point2.x) + fabs(point1.y - point2.y));
}

Tuesday, January 11, 2011

Creating a custom alert

//Background of AlertView is an image And you can change this image

UIAlertView *theAlert = [[[UIAlertView alloc] initWithTitle:@"Your Title"
message: @"Your Message Here"
delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];

[theAlert show];

UILabel *theTitle = [theAlert valueForKey:@"_titleLabel"];
[theTitle setTextColor:[UIColor redColor]];

UILabel *theBody = [theAlert valueForKey:@"_bodyTextLabel"];
[theBody setTextColor:[UIColor blueColor]];

UIImage *theImage = [UIImage imageNamed:@"Background.png"];
theImage = [theImage stretchableImageWithLeftCapWidth:16 topCapHeight:16];
CGSize theSize = [theAlert frame].size;

UIGraphicsBeginImageContext(theSize);
[theImage drawInRect:CGRectMake(0, 0, theSize.width, theSize.height)];
theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

[[theAlert layer] setContents:[theImage CGImage]];

Friday, January 7, 2011

validating & limit the character length of a TextField

*** This is a delegate method for UITextField


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];

if (textField.text.length >= MAX_LENGTH && range.length == 0)
{
return NO; // return NO to not change text
}
else
{
if(![string isEqualToString:filtered])
return NO;
else
return YES;
}
}

Wednesday, January 5, 2011

Using a custom image button in a navigation bar

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"myImage.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(blah) forControlEvents:UIControlEventTouchUpInside];
[button setFrame:CGRectMake(0, 0, 32, 32)];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

***the title of the nav controller will be auto resized this way. If you do it your way (subview of the nav bar) the text will go behind or ontop of the image

***it will also stay on the screen as you pop and push view controllers.

***once again, you can use an imageview as the custom view and not the button. Here is code:


UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,32,32)];
[iv setImage:[UIImage imageNamed:@"myImage.png"]];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:iv];
[iv release];

Vibrate iPhone device through application

-(void)vibrate
{
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

Vibrate iPhone device through application

-(void)vibrate
{
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

Jerking Effects with an ImageView in y-axis

-(void)shakeImageInY
{
CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.y"];
anim.values = [NSArray arrayWithObjects:[NSNumber numberWithFloat:-15],
[NSNumber numberWithFloat:15],
nil];
anim.duration = 0.2;
anim.autoreverses = YES;

anim.repeatCount = 0;
anim.additive = YES;
anim.fillMode=kCAFillModeForwards;
[imageView.layer addAnimation:anim forKey:@"wiggleTranslationY"];
}

Jerking Effects with an ImageView in x-axis

-(void)shakeImageInX
{
CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.y"];
anim.values = [NSArray arrayWithObjects:[NSNumber numberWithFloat:-15],
[NSNumber numberWithFloat:15],
nil];
anim.duration = 0.2;
anim.autoreverses = YES;

anim.repeatCount = 0;
anim.additive = YES;
anim.fillMode=kCAFillModeForwards;
[imageView.layer addAnimation:anim forKey:@"wiggleTranslationY"];
}

Friday, October 15, 2010

Rotating an image with bounds & unchanged ratio

- (void)scaleAndRotateImage:(UIImage *)image
{
int kMaxResolution = 320; // Or whatever

CGImageRef imgRef = image.CGImage;

CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);

CGAffineTransform transform = CGAffineTransformIdentity;
CGRect bounds = CGRectMake(0, 0, width, height);
if (width > kMaxResolution || height > kMaxResolution) {
CGFloat ratio = width/height;
if (ratio > 1) {
bounds.size.width = kMaxResolution;
bounds.size.height = bounds.size.width / ratio;
}
else {
bounds.size.height = kMaxResolution;
bounds.size.width = bounds.size.height * ratio;
}
}

CGFloat scaleRatio = bounds.size.width / width;
CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
CGFloat boundHeight;
UIImageOrientation orient = image.imageOrientation;
switch(orient) {

case UIImageOrientationUp: //EXIF = 1
transform = CGAffineTransformIdentity;
break;

case UIImageOrientationUpMirrored: //EXIF = 2
transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
break;

case UIImageOrientationDown: //EXIF = 3
transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
transform = CGAffineTransformRotate(transform, M_PI);
break;

case UIImageOrientationDownMirrored: //EXIF = 4
transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
transform = CGAffineTransformScale(transform, 1.0, -1.0);
break;

case UIImageOrientationLeftMirrored: //EXIF = 5
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;

case UIImageOrientationLeft: //EXIF = 6
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;

case UIImageOrientationRightMirrored: //EXIF = 7
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeScale(-1.0, 1.0);
transform = CGAffineTransformRotate(transform, M_PI / 2.0);
break;

case UIImageOrientationRight: //EXIF = 8
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
transform = CGAffineTransformRotate(transform, M_PI / 2.0);
break;

default:
[NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];

}

UIGraphicsBeginImageContext(bounds.size);

CGContextRef context = UIGraphicsGetCurrentContext();

if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
CGContextScaleCTM(context, -scaleRatio, scaleRatio);
CGContextTranslateCTM(context, -height, 0);
}
else {
CGContextScaleCTM(context, scaleRatio, -scaleRatio);
CGContextTranslateCTM(context, 0, -height);
}

CGContextConcatCTM(context, transform);

CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

[self setRotatedImage:imageCopy];
//return imageCopy;
}

Wednesday, September 29, 2010

Simple drawing through touches

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

mouseSwiped = NO;
UITouch *touch = [touches anyObject];

if ([touch tapCount] == 2) {
drawImage.image = nil;
return;
}

lastPoint = [touch locationInView:self.view];
lastPoint.y -= 20;

}


- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
mouseSwiped = YES;

UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self.view];
currentPoint.y -= 20;


UIGraphicsBeginImageContext(self.view.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

lastPoint = currentPoint;

}



- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

UITouch *touch = [touches anyObject];

if ([touch tapCount] == 2) {
drawImage.image = nil;
return;
}


if(!mouseSwiped) {
UIGraphicsBeginImageContext(self.view.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
CGContextFlush(UIGraphicsGetCurrentContext());
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
}

Tuesday, September 28, 2010

How to capture current screen through the app

-(IBAction)captureScreen:(id)sender
{
UIGraphicsBeginImageContext(webview.frame.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);
}

Tuesday, September 21, 2010

Selecting Photo from photo library through image picker

-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{

appDelegate.image = image;
[picker dismissModalViewControllerAnimated:YES];
}

Picking Image from camera or photo library

-(IBAction) camAction
{
if([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeCamera]){
UIImagePickerController *picker=[[UIImagePickerController alloc] init];
picker.delegate=self;
picker.sourceType=UIImagePickerControllerSourceTypeCamera;
//picker.allowsImageEditing = YES;
picker.editing=YES;
[self presentModalViewController:picker animated:YES];
[picker release];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"This device does not have any camera."
delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show];
[alert release];
}
}


-(IBAction) libraryAction
{
if([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypePhotoLibrary]){
UIImagePickerController *picker=[[UIImagePickerController alloc] init];
picker.delegate=self;
picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
//picker.allowsImageEditing = YES;
picker.editing=YES;
[self presentModalViewController:picker animated:YES];
[picker release];
}
}

Choosing Image through Action Sheet

-(IBAction)choosePictureButtonPressed
{


UIActionSheet *actionSheet = [[UIActionSheet alloc]
initWithTitle:nil
delegate:self
cancelButtonTitle:@"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:@"From Album",@"Camera",nil];

actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
actionSheet.cancelButtonIndex=2;
[actionSheet showInView:self.view];
[actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
[actionSheet release];
}

-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{

if(buttonIndex==0)
{
[self libraryAction];//:YES];
}
else if(buttonIndex == 1)
{
[self camAction];//:YES];
}
}

Monday, July 26, 2010

Photo Uploading in a web server through iPhone

-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
[picker dismissModalViewControllerAnimated:YES];
[picker dismissModalViewControllerAnimated:YES];
NSLog(@"image have been choosed");
CGRect newSize = CGRectMake(0, 0, 270.0f, 360.0f);
UIGraphicsBeginImageContext(newSize.size);
[image drawInRect:newSize];
UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
imageViewer.image = [imageCopy retain];
}



// post button's action

-(IBAction)postImage
{
NSInteger tmp = [[[NSUserDefaults standardUserDefaults] valueForKey:@"imageNameCount"] intValue];
tmp++;
[[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%d",tmp] forKey:@"imageNameCount"];
NSString *filename = [NSString stringWithFormat:@"myPhoto%@.jpg",[[NSUserDefaults standardUserDefaults] valueForKey:@"imageNameCount"]];
NSData *tmpData = UIImageJPEGRepresentation(imageViewer.image, 50);
[self uploadImage:tmpData filename:filename];
}


- (BOOL)uploadImage:(NSData *)imageData filename:(NSString *)filename{


NSString *urlString = @"http://test.prologsites.com/nc/upload_now.php";

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n",filename]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(returnString);
return ([returnString isEqualToString:@"OK"]);
}


// run the camera application

-(IBAction) camAction:(id)sender
{
if([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypePhotoLibrary]){
UIImagePickerController *picker=[[UIImagePickerController alloc] init];
picker.delegate=self;
picker.sourceType=UIImagePickerControllerSourceTypeCamera;
picker.editing=YES;
[self presentModalViewController:picker animated:YES];
[picker release];
}
}



// view the library to select photo

-(IBAction) libraryAction:(id)sender
{
if([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypePhotoLibrary]){
UIImagePickerController *picker=[[UIImagePickerController alloc] init];
picker.delegate=self;
picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
picker.editing=YES;
[self presentModalViewController:picker animated:YES];
[picker release];
}
}

Wednesday, July 7, 2010

Playing audio in iPhone

We can play audio files in the same way we played the video. The only difference is the file extensions. We just need to change extension of the file. That's it.