Monday, 3 June 2013

How to create vertical scroll view programmatically: cocos2d

To create a vertical scroll view with items, create an UIVIew and add ScrollView to it and add items to that ScrollView:

// in .h File //

        UIView *profileView;
        UIScrollView *verticalScroll;   

   

// in .m File //

    -(void)show_{

        // Create a UI View //
        profileView = [[UIView alloc] init];
        profileView.frame = CGRectMake(0, 0, 320, 480);
        profileView.backgroundColor = [UIColor blueColor];
        [[[CCDirector sharedDirector] openGLView] addSubview:profileView];
   
        // Create a UIScroll View //
        verticalScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 300, 420)];
        verticalScroll.backgroundColor = [UIColor yellowColor];
        verticalScroll.showsVerticalScrollIndicator = NO;
        verticalScroll.contentSize = CGSizeMake(300, 760);
        verticalScroll.center = CGPointMake(160, 250);
        verticalScroll.pagingEnabled = FALSE;
        [profileView addSubview:verticalScroll];
   
        // Create and add an UIImageView to the ScrollView //
        UIImageView *baseImg1 = [[UIImageView alloc] initWithFrame:CGRectMake(5, 20, 325, 65)];
        baseImg1.image = [UIImage imageNamed:@"imageName.png"];
        baseImg1.center =CGPointMake(150, 340);
        [verticalScroll addSubview:baseImg1];
        [baseImg1 release];
   
    }

Sunday, 2 June 2013

Using camera to take picture and save that to file: cocos2d

/* Using camera to take a photo */

    // in .h File //
        @interface HelloWorld : CCLayer <UIImagePickerControllerDelegate, UINavigationControllerDelegate>{
   
            UIImagePickerController *uip;
            UIImage *profileImage;
        }

    // in .m File //
        #import "AppDelegate.h"

        -(void)takePhoto{
            AppDelegate *appdel = [UIApplication sharedApplication].delegate;
   
            @try {
       
                uip = [[UIImagePickerController alloc] init] ;
                uip.sourceType = UIImagePickerControllerSourceTypeCamera;
                uip.allowsEditing = YES;
                uip.delegate = self;
            }
            @catch (NSException * e) {
                [uip release];
                uip = nil;
            }
            @finally {
                if(uip) {
                    [appdel.viewController presentModalViewController:uip animated:YES];
                }
            }
        }



    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
   
        profileImage=[info objectForKey:UIImagePickerControllerEditedImage];
        AppDelegate *appdel = [UIApplication sharedApplication].delegate;
        [appdel.viewController dismissModalViewControllerAnimated:YES];
        [uip release];
       
        [NSThread detachNewThreadSelector:@selector(writeImgToPath:) toTarget:self withObject:profileImage]; 
         
       
    }


// To write the image to file //
    -(void)writeImgToPath:(id)sender
    {
       
        NSAutoreleasePool *pool = [NSAutoreleasePool new];
        UIImage *image = sender;
        NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                           NSUserDomainMask,
                                                           YES);
        CGSize size;
        int currentProfileIndex = 1
        NSString *path = [[pathArr objectAtIndex:0]
                      stringByAppendingPathComponent:[NSString stringWithFormat:@"Img_%d.png",currentProfileIndex]];           
       
        size = CGSizeMake(120, 120);
        UIGraphicsBeginImageContext(size);
        [image drawInRect:CGRectMake(0, 0, 120, 120)];
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
   
        NSData *data = UIImagePNGRepresentation(image);
        [data writeToFile:path atomically:YES];
        NSLog(@"Saved.....");
       
        CGRect r = CGRectMake(0, 0, 80, 80);
        UIGraphicsBeginImageContext(r.size);
   
        UIImage *img1;
   
        [image drawInRect:r];
        img1 = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
       
        [pool release];
    }

How to read an image from file and display it in an UIImageView programmatically: cocos2d/Xcode

Reading an image from  file and displaying it on an ImageView is very siple as follows:

    -(void)CreateView{

        // Fetch saved image //

            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            NSString *imgPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"Img_%d.png",currentProfileIndex]];
            UIImage *img_1 = [UIImage imageWithContentsOfFile:imgPath];

      
        // Create an UIView //
       
            UIView *bgView = [[UIView alloc] init];
            bgView.frame = CGRectMake(240, 160, 10, 10);
            bgView.backgroundColor = [UIColor clearColor];
            [[[CCDirector sharedDirector]openGLView] addSubview:bgView];   


       // Create an UIImageView and display to display the image //

            UIImageView *bgImg = [[UIImageView alloc] initWithFrame:CGRectMake(240, 160, 50, 50)];
            bgImg.image = img_1;                    // Set the saved image to the UIImageView
            bgImg.center = CGPointMake(100, 100);
            [bgView addSubview:bgImg];
        }

How to create UITextField programmatically: cocos2d/Xcode

In .h file:

        @interface SceneName : CCLayer <UITextFieldDelegate>
       
            UITextField *nameField;

In .m file:

   // To create UITextField and assigning properties//

        -(void)createTextField{
           // create a UIView here(say profileView). Then do the following code //

            nameField = [[UITextField alloc] initWithFrame:CGRectMake(5, 20, 150, 30)];
            nameField.center = CGPointMake(285, 120);
            nameField.backgroundColor = [UIColor whiteColor];
            nameField.textAlignment = UITextAlignmentCenter;
            nameField.delegate = self;
            [nameField.layer setBorderColor:[[UIColor redColor]CGColor]];
            [nameField.layer setBorderWidth:1];
            nameField.layer.cornerRadius = 8;
            nameField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            [nameField addTarget:self action:@selector(valueChanged)
                                   forControlEvents:UIControlEventEditingChanged];
            [profileView addSubview:nameField];
        }

  
   // To resign first responder/keyboard //
   
        -(BOOL)textFieldShouldReturn:(UITextField *)textField
            {
                [textField resignFirstResponder];
                NSLog(@"%@ ",textField.text);                       // To get/print the data from the TextField
                return YES;
            }

        -(void)valueChanged{
            // To Limit text field text length //
            if ([nameField.text length] > 12) {
                nameField.text = [nameField.text substringToIndex:12];
            }
        }

    /*---------Some other important UITextField delegates---------*/
    -(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
        return YES;
    }

    - (BOOL) textFieldShouldBeginEditing:(UITextField *)textField{
        return YES;
    }

    - (void) textFieldDidBeginEditing:(UITextField *)textField
    {
   
    }
  

How to create and remove UIView and UIImageView programmatically: cocos2d

To create the UIView and UIImageView programmatically, you can use the following code:

To Create UIView:

        UIView *bgView = [[UIView alloc] init];
        bgView.frame = CGRectMake(0, 0, 480, 320);
        bgView.backgroundColor = [UIColor blueColor];
        [[[CCDirector sharedDirector]openGLView] addSubview:bgView];


To create UIImageView:

        UIImageView *bgImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 480, 320)];
        bgImg.image = [UIImage imageNamed:@"certificate.png"];
        bgImg.center = CGPointMake(240, 160);
        [bgView addSubview:bgImg]; 


For removing UIViews:

        [bgView removeFromSuperview];
        [bgView release];
        [bgImg removeFromSuperview];
        [bgImg release];

How to get device orientation programmatically: cocos2d

Tho get the device orientation programmatically, you can use the following code:


    if([[UIDevice currentDevice] orientation] == kCCDeviceOrientationPortrait) {
        NSLog(@"Portrait");
    }
    else if ([[UIDevice currentDevice] orientation] == kCCDeviceOrientationLandscapeLeft) {
        NSLog(@"LandscapeLeft");
    }
    else if ([[UIDevice currentDevice] orientation] == kCCDeviceOrientationLandscapeRight) {
        NSLog(@"LandscapeRight");
    }
    else if ([[UIDevice currentDevice] orientation] == kCCDeviceOrientationPortraitUpsideDown) {
        NSLog(@"PortraitUpsideDown");
    }

How to remove frame rate display from the app: cocos2d

To get rid of the frames per second display in a Cocos2d app, you can use the following method.


First, just go to the AppDelegate.m and  find out where the following line resides
:

          [director setDisplayFPS:YES];

Then just comment the above line as:

        // [director setDisplayFPS:YES];        // This will remove the frame rates from the app