Sunday, 2 June 2013

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];
        }

No comments:

Post a Comment