Powered By Blogger

Monday 10 December 2012

Image resizing and masking in IOS



Resize UIImage :

+(UIImage *)resizeImage:(UIImage *)image toSize:(CGSize)destSize{
    float currentHeight = image.size.height;
    float currentWidth = image.size.width;
    float liChange ;
    CGSize newSize ;
    if(currentWidth == currentHeight) // image is square
        {
             liChange = destSize.height / currentHeight;
             newSize.height = currentHeight * liChange;
             newSize.width = currentWidth * liChange;
            }
    else if(currentHeight > currentWidth) // image is landscape
         {
              liChange = destSize.width / currentWidth;
              newSize.height = currentHeight * liChange;
              newSize.width = destSize.width;
             }
    else        // image is Portrait
         {
             liChange = destSize.height / currentHeight;
             newSize.height= destSize.height;
             newSize.width = currentWidth * liChange;
             }
    
    
    UIGraphicsBeginImageContext( newSize );
    CGContextRef    context;
    UIImage      *outputImage = nil;
    
    context = UIGraphicsGetCurrentContext();
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
    [image drawInRect:CGRectMake( 0, 0, newSize.width, newSize.height )];
    outputImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    CGImageRef imageRef;
    int x = (newSize.width == destSize.width) ? 0 : (newSize.width - destSize.width)/2;
    int y = (newSize.height == destSize.height) ? 0 : (newSize.height - destSize.height )/2;
    if ( ( imageRef = CGImageCreateWithImageInRect( outputImage.CGImage, CGRectMake(x, y, destSize.width, destSize.height) ) ) ) {
         outputImage = [[UIImage alloc] initWithCGImage: imageRef] ;
         CGImageRelease( imageRef );
        }
     
    return outputImage;
}


Mask image:

+(UIImage *)maskImage:(UIImage *)image andMaskingImage:(UIImage *)maskingImage{
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGImageRef maskImageRef = [maskingImage CGImage];
    CGContextRef mainViewContentContext = CGBitmapContextCreate (NULL, maskingImage.size.width, maskingImage.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
    if (mainViewContentContext==NULL)
         return NULL;
    CGFloat ratio = 0;
    ratio = maskingImage.size.width/ image.size.width;
    if(ratio * image.size.height < maskingImage.size.height) {
         ratio = maskingImage.size.height/ image.size.height;
        }
    CGRect rect1= {{0, 0}, {maskingImage.size.width, maskingImage.size.height}};
    CGRect rect2= {{-((image.size.width*ratio)-maskingImage.size.width)/2 , -((image.size.height*ratio)-maskingImage.size.height)/2}, {image.size.width*ratio, image.size.height*ratio}};
    CGContextClipToMask(mainViewContentContext, rect1, maskImageRef);
    CGContextDrawImage(mainViewContentContext, rect2, image.CGImage);
    CGImageRef newImage = CGBitmapContextCreateImage(mainViewContentContext);
    CGContextRelease(mainViewContentContext);
    UIImage *theImage = [UIImage imageWithCGImage:newImage];
    CGImageRelease(newImage);
     // return the image
    return theImage;
}

More details please visit following link

http://mobiledevelopertips.com/cocoa/how-to-mask-an-image.html

Thursday 13 September 2012

How to handle view positions when keyboard hide and show time in Iphone:

Hi all, Today i want to share with all Iphone developers.
In this post My topic is ,

 How to handle view positions  when keyboard  hide and show time in Iphone:

1)KeyBoardViewController.xib you need to set delegate to all UItextFields



2)In the  KeyBoardViewController.h file, add the following code in bold:


#import <UIKit/UIKit.h>

@interface KeyBoardViewController : UIViewController<UIScrollViewDelegate,UITextFieldDelegate>
{
    IBOutlet UIScrollView *scrollView;
    UITextField *currentTextField;
    BOOL keyboardIsShown;
}
@property (nonatomic, retain) UIScrollView *scrollView;

@end

 3)In the  KeyBoardViewController.m file, add the following code in bold:


#import "KeyBoardViewController.h"

@interface KeyBoardViewController ()

@end

@implementation KeyBoardViewController
@synthesize scrollView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    scrollView.frame = CGRectMake(0, 0, 320, 460); 
    [scrollView setContentSize:CGSizeMake(320, 480)];
    [super viewDidLoad];
// Do any additional setup after loading the view.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
//—-before the View window appears—-
-(void) viewWillAppear:(BOOL)animated 
{
    //—-registers the notifications for keyboard—- 
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(keyboardDidShow:)
     name:UIKeyboardDidShowNotification object:self.view.window];
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(keyboardDidHide:)
     name:UIKeyboardDidHideNotification object:self.view.window];
    [super viewWillAppear:animated];
}

//—-when a
-(void) textFieldDidBeginEditing:(UITextField *)textFieldView 
    currentTextField = textFieldView;
}

//—-when the user taps on the return key on the keyboard—-
-(BOOL) textFieldShouldReturn:(UITextField *) textFieldView 
{
    [textFieldView resignFirstResponder];
    return NO;
}
//—-when a TextField view is done editing—-
-(void) textFieldDidEndEditing:(UITextField *) textFieldView 
{
    currentTextField = nil;
}
-(void) keyboardDidShow:(NSNotification *) notification 
{
    if (keyboardIsShown) return;
    NSDictionary* info = [notification userInfo];
    //—-obtain the size of the keyboard—-
    NSValue *aValue =
    [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect =[self.view convertRect:[aValue CGRectValue] fromView:nil];
    NSLog(@"%f", keyboardRect.size.height);
    //—-resize the scroll view (with keyboard)—-
    CGRect viewFrame = [scrollView frame];
    viewFrame.size.height -= keyboardRect.size.height;
    scrollView.frame = viewFrame;
    //—-scroll to the current text field—-
    CGRect textFieldRect = [currentTextField frame];
    [scrollView scrollRectToVisible:textFieldRect animated:YES];
    keyboardIsShown = YES;
}

//—-when the keyboard disappears—-
-(void) keyboardDidHide:(NSNotification *) notification { 
    NSDictionary* info = [notification userInfo];
    //—-obtain the size of the keyboard—-
    NSValue* aValue =[info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect =[self.view convertRect:[aValue CGRectValue] fromView:nil];
    //—-resize the scroll view back to the original size // (without keyboard)—-
    CGRect viewFrame = [scrollView frame]; viewFrame.size.height += keyboardRect.size.height; scrollView.frame = viewFrame;
    keyboardIsShown = NO
}
//—-before the View window disappear—-
-(void) viewWillDisappear:(BOOL)animated { //—-removes the notifications for keyboard—- 
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardDidHideNotification object:nil];
    [super viewWillDisappear:animated]; 
}
    
@end


Thank you 

Tuesday 27 March 2012

time comarision

If you want to calculate only time between two times **in same day** which are formatted as "HH:MM:SS" then it is pretty much easy

Use simple HttpDateParser and take any date which have proper format

like "Tue, 27 Mar 2012 09:11:37 GMT"

here we replace only time then you will get time in millies between two times

 

    String common="Tue, 27 Mar 2012 "; //09:11:37 GMT
                   String time1="1:50:10";
                   String time2="3:30:20";
                 long startTime = HttpDateParser.parse(common+time1+" GMT");
                 System.out.println("start time is :" + startTime);
                 long endTime =  HttpDateParser.parse(common+time2+" GMT");
                 System.out.println("end time is :" + endTime);
                 long diff = endTime - startTime;
               
                 SimpleDateFormat formate=new SimpleDateFormat("HH:mm:ss");
                 String formateddate=formate.formatLocal(diff);
                 System.out.println("Difference in Houres:"+formateddate);


I got output as

    [0.0] start time is :1332813010000
    [0.0] end time is :1332819020000
    [0.0] Difference in Houres:01:40:10


**Note : If you want to calculate between two different days
Here you need to pass date format should be proper like example: "YYYY-mm-dd hh:mm:ss"**

here i provide some sample example



    import java.util.Calendar;
   
    import net.rim.device.api.i18n.SimpleDateFormat;
    import net.rim.device.api.io.http.HttpDateParser;
    import net.rim.device.api.ui.Field;
    import net.rim.device.api.ui.FieldChangeListener;
    import net.rim.device.api.ui.component.ButtonField;
    import net.rim.device.api.ui.component.LabelField;
    import net.rim.device.api.ui.container.MainScreen;
    import net.rim.device.api.ui.picker.DateTimePicker;
   
    public final class Screen1 extends MainScreen implements FieldChangeListener
    {
        /**
         * Creates a new MyScreen object
         */
        ButtonField date1;
        ButtonField date2;
        ButtonField button;
        LabelField lbl;
        DateTimePicker picker;
        String str="";
        Calendar cal;   
       
        public Screen1()
        {  
           
            date1=new ButtonField("date1");
            date1.setChangeListener(this);
            add(date1);
           
            date2=new ButtonField("date2");
            date2.setChangeListener(this);
            add(date2);
           
            button = new ButtonField("Screen 1 ");
            button.setChangeListener(this);
            add(button);
            lbl=new LabelField();
            add(lbl);
        }
        public void fieldChanged(Field field, int context) {
            if(field==button){//Tue, 27 Mar 2012 09:11:37 GMT
          
                   System.out.println(date1.getLabel().toString()+"   "+date2.getLabel().toString());
                 long startTime = HttpDateParser.parse(date1.getLabel().toString());
                 System.out.println("start time is :" + startTime);
                 long endTime =  HttpDateParser.parse(date2.getLabel().toString());
                 System.out.println("end time is :" + endTime);
                 long diff = endTime - startTime;
          
                 SimpleDateFormat formate=new SimpleDateFormat("HH:mm:ss");
                 String formateddate=formate.formatLocal(diff);
                 System.out.println("Difference in Houres:"+formateddate);
                 lbl.setText("Time Between above dates is :"+formateddate);
            }else if(field==date1)
            {
                date1.setLabel(getDateTimeFromPicker().toString());                                   
           
            }else if(field==date2)
            {
                date2.setLabel(getDateTimeFromPicker().toString());
            }
   
        }
        private String getDateTimeFromPicker()
        {
            picker = DateTimePicker.createInstance( Calendar.getInstance(), "yyyy-MM-dd", "HH:mm:ss");
            picker.doModal();
            cal=picker.getDateTime();
            str="";
            if((cal.get(Calendar.MONTH)+1)<10)
                str=str+cal.get(Calendar.YEAR)+"-"+"0"+(cal.get(Calendar.MONTH)+1);
            else
                str=str+cal.get(Calendar.YEAR)+"-"+(cal.get(Calendar.MONTH)+1);
           
            if(cal.get(Calendar.DATE)<10)
                str=str+"-"+"0"+cal.get(Calendar.DATE);
            else
                str=str+"-"+cal.get(Calendar.DATE);
           
            if(cal.get(Calendar.HOUR_OF_DAY)<10)
                str=str+" "+"0"+cal.get(Calendar.HOUR_OF_DAY);
            else
                str=str+" "+cal.get(Calendar.HOUR_OF_DAY);
           
            if(cal.get(Calendar.MINUTE)<10)
                str=str+":"+"0"+cal.get(Calendar.MINUTE);
            else
                str=str+":"+cal.get(Calendar.MINUTE);
           
            if(cal.get(Calendar.SECOND)<10)
                str=str+":"+"0"+cal.get(Calendar.SECOND);
            else
                str=str+":"+cal.get(Calendar.SECOND);
            return str;
        }
    }

you can see as following output in your screen
![enter image description here][1]


  [1]: http://i.stack.imgur.com/4Rggl.png