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

Friday 23 December 2011

Retrive images from Sdcard


import java.io.InputStream;
import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
public class startup extends UiApplication{
    public static void main(String[] args) {
        startup start=new startup();
        start.enterEventDispatcher();
    }
    public startup() {
        pushScreen(new ImageView());
    }
}
public class ImageView extends MainScreen
{
    VerticalFieldManager vmgr;
    private String filepath="file:///SDCard/images/";
    public ImageView()
    {
        initGUI();
    }
    public void initGUI()
    {
        try
        {
            vmgr=new VerticalFieldManager(USE_ALL_HEIGHT|USE_ALL_WIDTH);
            Vector images=    getList(filepath);
            for(int i=0;i<images.size();i++)
            {
                Bitmap bit=getData(filepath+images.elementAt(i));
                Bitmap scale=new Bitmap(Display.getWidth(), 300);
                bit.scaleInto(scale, Bitmap.FILTER_LANCZOS);
                BitmapField field=new BitmapField(scale,Field.FOCUSABLE);
                vmgr.add(field);
            }
            add(vmgr);
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
    public Vector getList(String url)   
    {
        Vector contentVector=null;
        FileConnection fileConnection=null;
        try{
            fileConnection = (FileConnection) Connector.open(url);
       
            if (fileConnection.isDirectory()) {
                Enumeration directoryEnumerator = fileConnection.list();
                contentVector = new Vector();
                while (directoryEnumerator.hasMoreElements()) {
                    contentVector.addElement(directoryEnumerator.nextElement());
                }
            }
        }catch (Exception e) {
           
        }
        finally{
            if(fileConnection!=null){
                try {
                    fileConnection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return contentVector;
    }
     private Bitmap getData(String url)
     {   
         Bitmap bit_img=null;
         byte[] data = new byte[0];
         try
            {          
                FileConnection file = (FileConnection)Connector.open(url);
                int fileSize = (int)file.fileSize();
                data = new byte[fileSize];
                InputStream inputStream = file.openInputStream();           
                inputStream.read(data);
                EncodedImage bitmap = EncodedImage.createEncodedImage(data, 0,data.length); 
                bit_img=bitmap.getBitmap();
            }
            catch(Exception e)
            {
                System.out.println(e.toString());           
            }        
            return bit_img;         
     }
}

Thursday 22 December 2011

Blackberry application installation in to the mobile

Hi after signing project successfully we can find two types of files in Deliverables
1)standard 2)Web
in Standard Folder we can find
1)version number(if OS is 5.0 then we can find it 5.0.0)
2)projectname.alx
open that 5.0.0 folder here we can find many file types like .debug, .cod, csl, .cso ,.jar ,.jad ,.rapc these all are configuration files
NOTE:WE CAN FIND ONLY ONE .COD FILE AND .JAD FILE COPY THAT TWO FILES INTO ANY FILE SYSTEM INTO PC
Now open that .cod file and extract the all files into one particular folder suppose in my pc desktop i create a folder name DEVISEDEMO
i extract all .cod files into DEVISEDEMO Folder.
next i copy that .jad files into DEVISEDEMO folder
now i copy that DEVISEDEMO folder into Blackberry mobile SDCARD using any data cable
Now i disconnect that mobile from pc and open Memorycard ----> DEVISEDEMO after that click on .jad file now it can download all data regarding application after successfully installed one dialog will open.
This is one process otherwise copy all .cod and .jad files which are appear in the web folder to sdcard and after that same process
NOTE: YOU CAN NOT COMPARE ANDROID AND BLACKBERRY BECAUSE .APK FILE SIZE IS NOT RESTRICTED BUT BLACKBERRY WHEN WE SUCCESSFULLY SIGN THEN IT WILL CONVERT INTO .COD FILES MEANS SYSTEM UNDERSTANDABLE LANGUAGE. impermanent THING IS THAT ONE COD FILE CAN ONLY STORE 64KB DATA. IF IT CROSSED IT SIZE IT AUTOMATICALLY CREATE NEW .COD FILE. SO WE HAVE TO KEEP TRACK THESE INFORMATION WHICH FILE CONTINUATION IS WHICH FILE. FOR THIS PURPOSE .JAD FILE CAN KEEP ALL .COD FILES INFORMATION
if i made any wrong statements please correct that

Custom List view in blackberry

class sampleScreen extends MainScreen implements FieldChangeListener
{
    private CustomListField cu_field[];
    private Bitmap image=null;
    int size=8;
    public sampleScreen() {
        VerticalFieldManager vmanager=new VerticalFieldManager(VERTICAL_SCROLL|VERTICAL_SCROLLBAR){
            protected void sublayout(int maxWidth, int maxHeight) {
               
                super.sublayout(Display.getWidth(),Display.getHeight());
                setExtent(Display.getWidth(),Display.getHeight());
            }
        };
        cu_field=new CustomListField[size];
        for(int i=0;i<size;i++){
            image=Bitmap.getBitmapResource("sample_"+i+".jpg");
            cu_field[i]=new CustomListField("BlackBerry models that had a built-in mobile phone, were the first models that natively ran Java, and transmitted data over the normal 2G cellular network. RIM began to advertise these devices as email-capable mobile phones rather than as 2-way pagers.", image, "jan2011", 100, 100,Color.RED);
            cu_field[i].setChangeListener(this);
            vmanager.add(new SeparatorField());
            vmanager.add(cu_field[i]);
        }
        add(vmanager);
    }

    public void fieldChanged(Field field, int context) {
        // TODO Auto-generated method stub
        for(int i=0;i<size;i++){
            if(field==cu_field[i]){
                final int k=i;
                UiApplication.getUiApplication().invokeLater(new Runnable() {
                    public void run() {
                        Dialog.alert("You click on Item No "+k);
                    }
                });
            }
        }
    }
}

class CustomListField extends HorizontalFieldManager{

    private Bitmap scale_image;
    private int width=0;
    private int height=0;
    private int background_color=0;
    private BitmapField bitmap_field;
    private boolean flag=false;
    public CustomListField(String title, Bitmap image, String date,int image_width,int image_height,int background_color){
        super(NO_HORIZONTAL_SCROLL|USE_ALL_WIDTH);
        this.background_color=background_color;
        width=image_width;
        height=image_width;
        if(image!=null){
            scale_image=new Bitmap(image_width, image_height);
            image.scaleInto(scale_image, Bitmap.FILTER_LANCZOS);
            bitmap_field=new BitmapField(scale_image);
            flag=false;
            bitmap_field.setMargin(5, 5, 5, 5);
            add(bitmap_field);
        }
       
       
        VerticalFieldManager vmanager=new VerticalFieldManager(USE_ALL_WIDTH|Field.FIELD_VCENTER){
            protected void sublayout(int maxWidth, int maxHeight) {
                super.sublayout(Display.getWidth()-width, height);
                setExtent(Display.getWidth()-width, height);
            }
        };
        LabelField title_lbl=new LabelField("Title: "+title,Field.NON_FOCUSABLE|DrawStyle.ELLIPSIS);
        vmanager.add(title_lbl);
       
        LabelField date_lbl=new LabelField("Date: "+date,Field.NON_FOCUSABLE);
        vmanager.add(date_lbl);
       
        Font fon=title_lbl.getFont();
        int title_height=fon.getHeight();
       
        Font font=date_lbl.getFont();
        int date_height=font.getHeight();
        int pad=title_height+date_height;
        title_lbl.setPadding((height-pad)/2, 0, 0, 0);
        add(vmanager);
        add(new NullField(FOCUSABLE));
    }
   
    protected void sublayout(int maxWidth, int maxHeight) {
        super.sublayout(Display.getWidth(), height);
        setExtent(Display.getWidth(), height);
    }
    protected void paint(Graphics graphics) {
        if(flag)
        graphics.setBackgroundColor(background_color);
        graphics.clear();
        super.paint(graphics);
    }
    protected void onFocus(int direction) {
        super.onFocus(direction);
        flag=true;
        invalidate();
    }
    protected void onUnfocus() {
        invalidate();
        flag=false;
    }
    protected boolean navigationClick(int status, int time) {
       
        if(Touchscreen.isSupported()){
            return false;
        }else{
            fieldChangeNotify(1);
            return true;
        }
       
    }
    protected boolean touchEvent(TouchEvent message)
    {
        if (TouchEvent.CLICK == message.getEvent())
        {
           
            FieldChangeListener listener = getChangeListener();
            if (null != listener)
                this.setFocus();
                listener.fieldChanged(this, 1);
        }
        return super.touchEvent(message);
    }
}