Powered By Blogger

Friday, December 6, 2013

How to change image tint color in iphone sdk?

Hi all,


This category takes an image (presumably flat and solid-colored, like a toolbar icon), and fills its non-transparent pixels with a given color. You can optionally also specify a fractional opacity at which to composite the original image over the color-filled region, to give a tinting effect.

This is very useful for generating multiple different-colored versions of the same image, for example 'disabled' or 'highlighted' states of the same basic image, without having to make multiple different-colored bitmap image files.

So, Just make two different files named as : "UIImage+Tint.h" and  "UIImage+Tint.m"


1) For  "UIImage+Tint.h" contents will be ..

#import <UIKit/UIKit.h>

@interface UIImage (ImageTint)

- (UIImage *)imageTintedWithColor:(UIColor *)color;
@end


2) For  "UIImage+Tint.m" contents will be ..
 
#import "UIImage+Tint.h"

@implementation UIImage (ImageTint)

- (UIImage *)imageTintedWithColor:(UIColor *)color
{
    if (color) {
        // Construct new image the same size as this one.
        UIImage *image;
        UIGraphicsBeginImageContextWithOptions([self size], NO, 0.0); // 0.0 for scale means "scale for device's main screen".
        CGRect rect = CGRectZero;
        rect.size = [self size];
       
        // tint the image
        [self drawInRect:rect];
        [color set];
        UIRectFillUsingBlendMode(rect, kCGBlendModeMultiply);
       
        // restore alpha channel
        [self drawInRect:rect blendMode:kCGBlendModeDestinationIn alpha:1.0f];
       
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
       
        return image;
    }
   
    return self;
}
@end

3) Now you can import "UIImage+Tint.h" file into your class where you want colorful images and do below code.

   UIImage *imgMail = [UIImage imageNamed:@"icon_mail.png"];
    imgMail = [imgMail imageTintedWithColor:MENU_COLOR]; //Colorful image


Important Note : Images will be preferred transparent only .

Thanks,
Nilesh M. Prajapati


Tuesday, October 22, 2013

How can we extract numbers from a string in iPhone?

Hi,

Here is the way to separate numbers from a mixed character string. For this , anybody can use "NSScanner" in their own way. I use this one to filter numbers from the given input string. Please have look ...

For Example : 

NSString *string = @"45#%ds32(())_*x 34";
NSMutableString *newStrStrip = [NSMutableString
        stringWithCapacity:newStrStrip.length];

NSScanner *scanner = [NSScanner scannerWithString:string];
NSCharacterSet *numbers = [NSCharacterSet
        characterSetWithCharactersInString:@"0123456789"];

while ([scanner isAtEnd] == NO)
{
  NSString *buffer;
      if ([scanner scanCharactersFromSet:numbers intoString:&buffer])
     {
          [newStrStrip appendString:buffer];
     }
     else
     {
          [scanner setScanLocation:([scanner scanLocation] + 1)];
     }
}

NSLog(@"OUTPUT : %@", newStrStrip);  // "OUTPUT : 453234"


Regards,
Nilesh M. Prajapati

Saturday, July 20, 2013

Custom switch in iPhone

Hi,
In my recent project, I need to make a custom switch having different colors depending upon theme selection.
Now , I have a solution for that... Make two class files with extension ".h" & ".m". Original Content is available at  HERE. I have made some modifications to the original contents as per my requirements.

SECTION 1 :
 -------------------------------------------------

#import <UIKit/UIKit.h>

@interface CustomSwitch : UIControl

@property(nonatomic, retain) UIColor *tintColor;
@property(nonatomic, retain) UIColor *onTintColor;
@property(nonatomic, assign) UIColor *offTintColor;
@property(nonatomic, assign) UIColor *thumbTintColor;
@property(nonatomic,getter=isOn) BOOL on;


- (id)initWithFrame:(CGRect)frame;
- (void)setOn:(BOOL)on animated:(BOOL)animated;

@end


SECTION 2 :
  -------------------------------------------------

#import "CustomSwitch.h"
#import <QuartzCore/QuartzCore.h>


@interface CustomSwitch () <UIGestureRecognizerDelegate> 

{
    CAShapeLayer *_thumbLayer;
    CAShapeLayer *_fillLayer;
    CAShapeLayer *_backLayer;
    BOOL _dragging;
    BOOL _on;
}
@property (nonatomic, assign) BOOL pressed;
- (void) setBackgroundOn:(BOOL)on animated:(BOOL)animated;
- (void) showFillLayer:(BOOL)show animated:(BOOL)animated;
- (CGRect) thumbFrameForState:(BOOL)isOn;
@end

@implementation
CustomSwitch

 
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self configure];
    }
    return self;
}

- (void) awakeFromNib {
    [self configure];
}

- (void) configure {
    //Check width > height
    if (self.frame.size.height > self.frame.size.width*0.65) {
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, ceilf(0.6*self.frame.size.width));
    }
   
    [self setBackgroundColor:[UIColor clearColor]];
    self.onTintColor = [UIColor colorWithRed:0.27f green:0.85f blue:0.37f alpha:1.00f];
    self.tintColor = [UIColor colorWithRed:0.90f green:0.90f blue:0.90f alpha:1.00f];
    _on = NO;
    _pressed = NO;
    _dragging = NO;
   
   
    _backLayer = [[CAShapeLayer layer] retain];
    _backLayer.backgroundColor = [[UIColor clearColor] CGColor];
    _backLayer.frame = self.bounds;
    _backLayer.cornerRadius = self.bounds.size.height/2.0;
    CGPathRef path1 = [UIBezierPath bezierPathWithRoundedRect:_backLayer.bounds cornerRadius:floorf(_backLayer.bounds.size.height/2.0)].CGPath;
    _backLayer.path = path1;
    [_backLayer setValue:[NSNumber numberWithBool:NO] forKey:@"isOn"];
    _backLayer.fillColor = [_tintColor CGColor];
    [self.layer addSublayer:_backLayer];
   
    _fillLayer = [[CAShapeLayer layer] retain];
    _fillLayer.backgroundColor = [[UIColor clearColor] CGColor];
    _fillLayer.frame = CGRectInset(self.bounds, 1.5, 1.5);
    CGPathRef path = [UIBezierPath bezierPathWithRoundedRect:_fillLayer.bounds cornerRadius:floorf(_fillLayer.bounds.size.height/2.0)].CGPath;
    _fillLayer.path = path;
    [_fillLayer setValue:[NSNumber numberWithBool:YES] forKey:@"isVisible"];
    _fillLayer.fillColor = [[UIColor whiteColor] CGColor];
    [self.layer addSublayer:_fillLayer];
   
   
    _thumbLayer = [[CAShapeLayer layer] retain];
    _thumbLayer.backgroundColor = [[UIColor clearColor] CGColor];
    _thumbLayer.frame = CGRectMake(1.0, 1.0, self.bounds.size.height-2.0, self.bounds.size.height-2.0);
    _thumbLayer.cornerRadius = self.bounds.size.height/2.0;
    CGPathRef knobPath = [UIBezierPath bezierPathWithRoundedRect:_thumbLayer.bounds cornerRadius:floorf(_thumbLayer.bounds.size.height/2.0)].CGPath;
    _thumbLayer.path = knobPath;
    _thumbLayer.fillColor = [UIColor whiteColor].CGColor;
    _thumbLayer.shadowColor = [UIColor blackColor].CGColor;
    _thumbLayer.shadowOffset = CGSizeMake(0.0, 2.0);
    _thumbLayer.shadowRadius = 3.0;
    _thumbLayer.shadowOpacity = 0.1;
    [self.layer addSublayer:_thumbLayer];
   
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                            action:@selector(tapped:)];
    [tapGestureRecognizer setDelegate:self];
    [self addGestureRecognizer:tapGestureRecognizer];
   
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                                            action:@selector(toggleDragged:)];
    //[panGestureRecognizer requireGestureRecognizerToFail:tapGestureRecognizer];
    [panGestureRecognizer setDelegate:self];
    [self addGestureRecognizer:panGestureRecognizer];
   
    [tapGestureRecognizer release];
    [panGestureRecognizer release];
}

#pragma mark -
#pragma mark Animations


- (BOOL) isOn {
    return _on;
}

- (void) setOn:(BOOL)on {
    [self setOn:on animated:NO];
}

- (void)setOn:(BOOL)on animated:(BOOL)animated {
   
    if (_on != on) {
        _on = on;
        [self sendActionsForControlEvents:UIControlEventValueChanged];
    }
    if (animated) {
        [CATransaction begin];
        [CATransaction setAnimationDuration:0.3];
        [CATransaction setDisableActions:NO];
        _thumbLayer.frame = [self thumbFrameForState:_on];
        [CATransaction commit];
    }else {
        [CATransaction setDisableActions:YES];
        _thumbLayer.frame = [self thumbFrameForState:_on];
    }
    [self setBackgroundOn:_on animated:animated];
    [self showFillLayer:!_on animated:animated];
}

- (void) setBackgroundOn:(BOOL)on animated:(BOOL)animated {
    BOOL isOn = [[_backLayer valueForKey:@"isOn"] boolValue];
    if (on != isOn) {
        [_backLayer setValue:[NSNumber numberWithBool:on] forKey:@"isOn"];
        if (animated) {
            CABasicAnimation *animateColor = [CABasicAnimation animationWithKeyPath:@"fillColor"];
            animateColor.duration = 0.22;
            animateColor.fromValue = on ? (id)_tintColor.CGColor : (id)_onTintColor.CGColor;
            animateColor.toValue = on ? (id)_onTintColor.CGColor : (id)_tintColor.CGColor;
            animateColor.removedOnCompletion = NO;
            animateColor.fillMode = kCAFillModeForwards;
            [_backLayer addAnimation:animateColor forKey:@"animateColor"];
            [CATransaction commit];
        }else {
            [_backLayer removeAllAnimations];
            _backLayer.fillColor = on ? _onTintColor.CGColor : _tintColor.CGColor;
        }
    }
}

- (void) showFillLayer:(BOOL)show animated:(BOOL)animated {
    BOOL isVisible = [[_fillLayer valueForKey:@"isVisible"] boolValue];
    if (isVisible != show) {
        [_fillLayer setValue:[NSNumber numberWithBool:show] forKey:@"isVisible"];
        CGFloat scale = show ? 1.0 : 0.0;
        if (animated) {
            CGFloat from = show ? 0.0 : 1.0;
            CABasicAnimation *animateScale = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
            animateScale.duration = 0.22;
            animateScale.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(from, from, 1.0)];
            animateScale.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(scale, scale, 1.0)];
            animateScale.removedOnCompletion = NO;
            animateScale.fillMode = kCAFillModeForwards;
            animateScale.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
            [_fillLayer addAnimation:animateScale forKey:@"animateScale"];
        }else {
            [_fillLayer removeAllAnimations];
            _fillLayer.transform = CATransform3DMakeScale(scale,scale,1.0);
        }
    }
}

- (void) setPressed:(BOOL)pressed {
    if (_pressed != pressed) {
        _pressed = pressed;
       
        if (!_on) {
            [self showFillLayer:!_pressed animated:YES];
        }
    }
}

#pragma mark -
#pragma mark Appearance


- (void) setTintColor:(UIColor *)tintColor {
    _tintColor = [tintColor retain];
    if (![[_backLayer valueForKey:@"isOn"] boolValue]) {
        _backLayer.fillColor = [_tintColor CGColor];
    }
}

- (void) setOnTintColor:(UIColor *)onTintColor {
    _onTintColor = [onTintColor retain];
    if ([[_backLayer valueForKey:@"isOn"] boolValue]) {
        _backLayer.fillColor = [_onTintColor CGColor];
    }
}

- (void) setOffTintColor:(UIColor *)offTintColor {
    _fillLayer.fillColor = [offTintColor CGColor];
}

- (UIColor *) offTintColor {
    return [UIColor colorWithCGColor:_fillLayer.fillColor];
}

- (void) setThumbTintColor:(UIColor *)thumbTintColor {
    _thumbLayer.fillColor = [thumbTintColor CGColor];
}

- (UIColor *) thumbTintColor {
    return [UIColor colorWithCGColor:_thumbLayer.fillColor];
}

#pragma mark -
#pragma mark Interaction


- (void)tapped:(UITapGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateEnded)
        [self setOn:!self.on animated:YES];
}

- (void)toggleDragged:(UIPanGestureRecognizer *)gesture
{
    CGFloat minToggleX = 1.0;
    CGFloat maxToggleX = self.bounds.size.width-self.bounds.size.height+1.0;
   
    if (gesture.state == UIGestureRecognizerStateBegan)
    {
        self.pressed = YES;
        _dragging = YES;
    }
    else if (gesture.state == UIGestureRecognizerStateChanged)
    {
        CGPoint translation = [gesture translationInView:self];
       
        [CATransaction setDisableActions:YES];
       
        self.pressed = YES;
       
        CGFloat newX = _thumbLayer.frame.origin.x + translation.x;
        if (newX < minToggleX) newX = minToggleX;
        if (newX > maxToggleX) newX = maxToggleX;
        _thumbLayer.frame = CGRectMake(newX,
                                       _thumbLayer.frame.origin.y,
                                       _thumbLayer.frame.size.width,
                                       _thumbLayer.frame.size.height);
       
        if (CGRectGetMidX(_thumbLayer.frame) > CGRectGetMidX(self.bounds)
            && ![[_backLayer valueForKey:@"isOn"] boolValue]) {
            [self setBackgroundOn:YES animated:YES];
        }else if (CGRectGetMidX(_thumbLayer.frame) < CGRectGetMidX(self.bounds)
                  && [[_backLayer valueForKey:@"isOn"] boolValue]){
            [self setBackgroundOn:NO animated:YES];
        }
       
       
        [gesture setTranslation:CGPointZero inView:self];
    }
    else if (gesture.state == UIGestureRecognizerStateEnded)
    {
        CGFloat toggleCenter = CGRectGetMidX(_thumbLayer.frame);
        [self setOn:(toggleCenter > CGRectGetMidX(self.bounds)) animated:YES];
        _dragging = NO;
        self.pressed = NO;
    }
   
    CGPoint locationOfTouch = [gesture locationInView:self];
    if (CGRectContainsPoint(self.bounds, locationOfTouch))
        [self sendActionsForControlEvents:UIControlEventTouchDragInside];
    else
        [self sendActionsForControlEvents:UIControlEventTouchDragOutside];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
   
    self.pressed = YES;
   
    [self sendActionsForControlEvents:UIControlEventTouchDown];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];
    if (!_dragging) {
        self.pressed = NO;
    }
    [self sendActionsForControlEvents:UIControlEventTouchUpInside];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesCancelled:touches withEvent:event];
    if (!_dragging) {
        self.pressed = NO;
    }
    [self sendActionsForControlEvents:UIControlEventTouchUpOutside];
}

#pragma mark -
#pragma mark Thumb Frame


- (CGRect) thumbFrameForState:(BOOL)isOn {
    return CGRectMake(isOn ? self.bounds.size.width-self.bounds.size.height+1.0 : 1.0,
                      1.0,
                      self.bounds.size.height-2.0,
                      self.bounds.size.height-2.0);
}

#pragma mark -
#pragma mark Dealloc

- (void) dealloc {
    [_tintColor release], _tintColor = nil;
    [_onTintColor release], _onTintColor = nil;
   
    [_thumbLayer release], _thumbLayer = nil;
    [_fillLayer release], _fillLayer = nil;
    [_backLayer release], _backLayer = nil;
    [super dealloc];
}

@end
 

Thanks ,
Nilesh M. Prajapati

Monday, July 1, 2013

Custom refresh control in iPhone

Hi,
Everyone,

Did you ever use "Custom Refresh Control" in your iOS application? I recently implemented this concept in my one of code. There's a ready-made control available called "ODRefreshControl"

You just need to import to files into your project resource. "ODRefreshControl.h" & "ODRefreshControl.m". Please check below lines to use it in your code.

*******For Example :

1) Import Files : "ODRefreshControl.h" & "ODRefreshControl.m"
2) Put this into your class file.

- (void)viewDidLoad
{

    ODRefreshControl *refreshControl = [[ODRefreshControl alloc] initInScrollView:tbl_tableView]; // Assign your view in which you want to use it. I used it in my UITableViewController.
    [refreshControl addTarget:self action:@selector(dropViewDidBeginRefreshing:)  forControlEvents:UIControlEventValueChanged];

 [super viewDidLoad];
}

#pragma mark ---------------
#pragma mark UITableView Pull-To-Refresh Management
#pragma mark ---------------

- (void)dropViewDidBeginRefreshing:(ODRefreshControl *)refreshControl
{
    double delayInSeconds = 1.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [refreshControl endRefreshing];
          // write your own refresh method here which you want to call.
    });
}

Thanks,
Nilesh M. Prajapati

Saturday, June 1, 2013

How to show direction inside a Mapview with iOS 6.0 in iphone?

Hey everyone,
  --- Now, with iOS 6.0 , To show direction from source - destination location in Apple's map application. Please check the below code to show the direction into MKMapView.

*** For Example :

CLLocationCoordinate2D coordinate;
coordinate.latitude = 0.0f; // Latitude of your source location
coordinate.longitude = 0.0f; // Longitude of your source location

        MKPlacemark* place = [[MKPlacemark alloc] initWithCoordinate: coordinate addressDictionary: nil];
        MKMapItem* destination = [[MKMapItem alloc] initWithPlacemark: place];
        destination.name = @"Address of your destination";
        NSArray* items = [[NSArray alloc] initWithObjects: destination, nil];
        NSDictionary* options = [[NSDictionary alloc] initWithObjectsAndKeys:
                                 MKLaunchOptionsDirectionsModeDriving,
                                 MKLaunchOptionsDirectionsModeKey, nil];
        [MKMapItem openMapsWithItems: items launchOptions: options];



Thanks,
Nilesh M. Prajapati

Thursday, May 23, 2013

What should be the alternative of horizontal scrolling table in iOS?

Hi,
Dear readers,

Now a days, I came across a new requirement of horizontal scrolling table view. I made some research for it and I found a new library as a unique solution for this. The library is known as "iCarousel" library. You just need to add that 2 files into your project source and after then you can import ".h"(header) file in your class where-ever you want to make such view effect.

Download Link : https://github.com/nicklockwood/iCarousel



After downloading two source files "iCarousel.h" & "iCarousel.m". Follow the below steps to integrate it in your project.

*** Step 1: Create a view of iCarousel in header file and bind it with .XIB file.
    - For ex. : IBOutlet iCarousel *carousel;

*** Step 2: Then place its data-source and delegate methods in implementation section of a view controller.

*** Step 3: Set the delegate of a iCarousel.

*** Step 4: Set the type of a iCarousel in ViewDidLoad method.

- (void)viewDidLoad
{
       [super viewDidLoad];

        carousel.type = iCarouselTypeLinear;
        carousel.vertical = NO;
        carousel.scrollOffset = 1.0;
        carousel.centerItemWhenSelected = NO;
        carousel.stopAtItemBoundary = YES;
        carousel.scrollToItemBoundary = NO;
}

***Step 5: And finally put the below code into implementation section of a view controller.

#pragma mark -------------------
#pragma mark iCarousel Delegate methods
#pragma mark -------------------


- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
    //generate 100 buttons
    //normally we'd use a backing array
    //as shown in the basic iOS example
    //but for this example we haven't bothered
    return [businessArr count];
}

- (UIView *)carousel:(iCarousel *)carousel1 viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
        //create new view if no view is available for recycling
        CustomBusinessListingCell_iPad *businessListingView  = (CustomBusinessListingCell_iPad *)[[[NSBundle mainBundle]loadNibNamed:@"CustomBusinessListingCell_iPad" owner:self options:nil] objectAtIndex:0];
        businessListingView.frame =  CGRectMake(0, 0, LIST_VIEW_WIDTH, LIST_VIEW_HEIGHT);
        businessListingView.tag = index;
        businessListingView.lblBusinessName.verticalAlignment = BAVerticalAlignmentBottom;

        businessListingView.btnBook.tag = index;
        [businessListingView.btnBook addTarget:self action:@selector(btnBookClicked:) forControlEvents:UIControlEventTouchUpInside];
       
        businessListingView.btnBookmark.tag = index;
        [businessListingView.btnBookmark addTarget:self action:@selector(priceClicked:) forControlEvents:UIControlEventTouchUpInside];
       
         //NSLog(@"BusinessImage : %@",[[businessArr objectAtIndex:index] valueForKey:@"BusinessImage"]);
       
        [businessListingView setBusinessValue:[businessArr objectAtIndex:index]];
       
        if (index==[businessArr count]-1)
        {
            // ask next page only if we haven't reached last page
            if([businessArr count] < totalRecords)
            {
                if (!isLoadmore)
                {
                    isLoadmore = YES;
                    pageIndex = pageIndex+1;
                    [self loadNewData];
                }
            }
        }
        return businessListingView;
}

-(void)setCarouselPosition
{
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
    if ((orientation == UIInterfaceOrientationPortrait) || (orientation == UIInterfaceOrientationPortraitUpsideDown)) {
        [carousel scrollToOffset:0.6 duration:0.0];
    }
    else if((orientation == UIInterfaceOrientationLandscapeLeft) || (orientation == UIInterfaceOrientationLandscapeRight))
    {
        [carousel scrollToOffset:1.1 duration:0.0];
    }
}

- (CGFloat)carousel:(iCarousel *)_carousel valueForOption:(iCarouselOption)option withDefault:(CGFloat)value
{
    //customize carousel display
    switch (option)
    {
        case iCarouselOptionSpacing:
        {
            //add a bit of spacing between the item views
            return value * 1.08f;
        }
        case iCarouselOptionVisibleItems:
        {
            return 5;
        }
        default:
        {
            return value;
        }
    }
}

- (void)carouselDidEndScrollingAnimation:(iCarousel *)carousel1
{
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
    if ((orientation == UIInterfaceOrientationPortrait) || (orientation == UIInterfaceOrientationPortraitUpsideDown)) {
        if (carousel1.scrollOffset < 0.6) {
            [UIView beginAnimations:@"" context:nil];
            [UIView setAnimationDuration:0.7];
            [carousel1 scrollToOffset:0.6 duration:0.0];
            [UIView commitAnimations];
        }
    }
    else if ((orientation == UIInterfaceOrientationLandscapeLeft) || (orientation == UIInterfaceOrientationLandscapeRight))
    {
        if (carousel1.scrollOffset < 1.1) {
            [UIView beginAnimations:@"" context:nil];
            [UIView setAnimationDuration:0.7];
            [carousel1 scrollToOffset:1.1 duration:0.0];
            [UIView commitAnimations];
        }
    }
}

- (void)carouselDidEndDragging:(iCarousel *)carousel1 willDecelerate:(BOOL)decelerate
{
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
    if ((orientation == UIInterfaceOrientationPortrait) || (orientation == UIInterfaceOrientationPortraitUpsideDown)) {
        if (carousel1.scrollOffset < 0.6) {
            [UIView beginAnimations:@"" context:nil];
            [UIView setAnimationDuration:0.7];
            [carousel1 scrollToOffset:0.6 duration:0.0];
            [UIView commitAnimations];
        }
    }
    else if ((orientation == UIInterfaceOrientationLandscapeLeft) || (orientation == UIInterfaceOrientationLandscapeRight))
    {
        if (carousel1.scrollOffset < 1.1) {
            [UIView beginAnimations:@"" context:nil];
            [UIView setAnimationDuration:0.7];
            [carousel1 scrollToOffset:1.1 duration:0.0];
            [UIView commitAnimations];
        }
    }
}

Thanks,
Nilesh M. Prajapati

How to resolve apple's UDID issue for Push Notification in iPhone?

Hi,
Everyone,

Rumors say that Apple starts to prohibit the use of UDID in iOS applications from iOS 6.0 and onwards. You can use below solution for  < & >=  iOS 6.0 .

- The device token (used by APNS) and the UDID are two different things. They have nothing to do with each other.

- You obtain the device token for push notifications in your app delegate's application:didRegisterForRemoteNotificationsWithDeviceToken: method.


- The documentation notes the following:
The device token is different from the uniqueIdentifier property of UIDevice because, for security and privacy reasons, it must change when the device is wiped.


#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)

NSString *deviceID = nil;

#pragma mark -------------------
#pragma mark UIApplication methods
#pragma mark -------------------

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if (![[NSUserDefaults standardUserDefaults] valueForKey:@"UUID"]) {
        if (SYSTEM_VERSION_LESS_THAN(@"6.0")) {
            self.deviceID = [[self GetUUID] retain];
        }
        else{
            NSUUID* udid= [UIDevice currentDevice].identifierForVendor;
            self.deviceID = [[udid UUIDString] retain];
        }
        [[NSUserDefaults standardUserDefaults] setValue:self.deviceID forKey:@"UUID"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    else{
        self.deviceID = [[[NSUserDefaults standardUserDefaults] valueForKey:@"UUID"] retain];
    }
}

#pragma mark -------------------
#pragma mark Push notification methods
#pragma mark -------------------

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    //NSLog(@"My token is: %@", deviceToken);
    NSString *devicetoken = [[[[deviceToken description]
                               stringByReplacingOccurrencesOfString:@"<"withString:@""]
                              stringByReplacingOccurrencesOfString:@">" withString:@""]
                             stringByReplacingOccurrencesOfString: @" " withString: @""];
    [self updateToken:devicetoken];
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    //NSLog(@"Failed to get token, error: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // get state
    UIApplicationState state=[application applicationState];
    if(state== UIApplicationStateActive)
        self.badgeCount=[[[userInfo valueForKey:@"aps"] valueForKey:@"badge"] intValue];
    else
        self.badgeCount= [UIApplication sharedApplication].applicationIconBadgeNumber;
}

- (NSString *)GetUUID
{
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    return [(NSString *)string autorelease];
}

Thanks, 
Nilesh M. Prajapati

Thursday, February 21, 2013

How to capture snapshot of UIWebview in iPhone?


Hi everyone,
Have you ever tried to take a picture of "UIWebView" in any of your applications? Now, you can do it by following below code in your project. You can use scrollview property of UIWebView in iOS 5.0 and later SDK.

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

For example:

#pragma mark --------------------
#pragma mark Take screenshot from Webview
#pragma mark --------------------


UIWebView *receiptWeb;
- (UIImage *)takeScreenshotFromWebview
{
    UIImage *img = nil;
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"5.0"))
    {
        UIGraphicsBeginImageContextWithOptions(receiptWeb.scrollView.contentSize, receiptWeb.scrollView.opaque, 0.0);
        {
            CGPoint savedContentOffset = receiptWeb.scrollView.contentOffset;
            CGRect savedFrame = receiptWeb.scrollView.frame;
          
            receiptWeb.scrollView.contentOffset = CGPointZero;
            receiptWeb.scrollView.frame = CGRectMake(0, 0, receiptWeb.scrollView.contentSize.width, receiptWeb.scrollView.contentSize.height);
            [receiptWeb.scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
            img = UIGraphicsGetImageFromCurrentImageContext();
          
            receiptWeb.scrollView.contentOffset = savedContentOffset;
            receiptWeb.scrollView.frame = savedFrame;
        }
        UIGraphicsEndImageContext();
    }
    else
    {
        for (id subview in receiptWeb.subviews)
        {
            if ([subview isKindOfClass:[UIScrollView class]])
            {
                UIScrollView *scrollView = (UIScrollView *)subview;
                UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, scrollView.opaque, 0.0);
                {
                    CGPoint savedContentOffset = scrollView.contentOffset;
                    CGRect savedFrame = scrollView.frame;
                  
                    scrollView.contentOffset = CGPointZero;
                    scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
                    [scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
                    img = UIGraphicsGetImageFromCurrentImageContext();
                  
                    scrollView.contentOffset = savedContentOffset;
                    scrollView.frame = savedFrame;
                }
                UIGraphicsEndImageContext();
            }
        }
    }
    return img;
}

Regards,
Nilesh Prajapati

Tuesday, February 19, 2013

Best printer sdk for iPhone

Hey everyone,
Now I found one more good things regarding printing in iPhone SDK. I found "STAR MACRONICS" printers having their own SDKs for Both iOS and android devices. By using this SDK, You can easily integrate POS printers and as well as bluetooth, USB printers with your application.

Please take a look to below given link from where you can download SDK and its manual for integration.


Documentation link http://www.starmicronics.com/support/SDKDocumentation.aspx


Regards,
Nilesh Prajapati

Monday, January 28, 2013

how to integrate barcode scanning in iphone?


Hi everyone,
Recently, I have worked with Barcode scanning project for iPhone/iPad development. It was good time for me to work on such project. So, I'm going to share information about that SDK.

SDK Name : ZXingObjC
SDK URL path : https://github.com/TheLevelUp/ZXingObjC

You need to add following frameworks in your projects to make it works.
For an iOS app:
  • AVFoundation.framework
  • CoreMedia.framework
  • CoreGraphics.framework
  • CoreVideo.framework
  • ImageIO.framework

Download the sdk and start to implement. if you find any difficulty then you can ask me.

Thanks,
Nilesh M. Prajapati

Saturday, January 19, 2013

how create shadow image in iPhone?

Hi all,
Follow below steps to create lazy image-view with image having shadow effect.

Step 1 : Create two files named as "NPImageView.h"  and "NPImageView.m"

#import <UIKit/UIKit.h>


@interface NPImageView : UIImageView

+ (NSOperationQueue *)processingQueue;
+ (NSCache *)processedImageCache;


@property (nonatomic, assign, getter = isAsynchronous) BOOL asynchronous;
@property (nonatomic, assign) CGFloat reflectionGap;
@property (nonatomic, assign) CGFloat reflectionScale;
@property (nonatomic, assign) CGFloat reflectionAlpha;
@property (nonatomic, strong) UIColor *shadowColor;
@property (nonatomic, assign) CGSize shadowOffset;
@property (nonatomic, assign) CGFloat shadowBlur;
@property (nonatomic, assign) CGFloat cornerRadius;
@property (nonatomic, strong) UIImage *processedImage;

@property (nonatomic, copy) UIImage *(^customEffectsBlock)(UIImage *image);
@property (nonatomic, copy) NSString *cacheKey;

- (void)setImageWithContentsOfFile:(NSString *)file;
- (void)setImageWithContentsOfURL:(NSURL *)URL;

@end




#import "FXImageView.h"
#import "UIImage+FX.h"
#import <objc/message.h>


@interface NPImageOperation : NSOperation

@property (nonatomic, strong) NPImageView *target;

@end


@interface NPImageView ()

@property (nonatomic, assign) UIActivityIndicatorView *loading;
@property (nonatomic, strong) UIImage *originalImage;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) NSURL *imageContentURL;

- (void)processImage;

@end


@implementation NPImageOperation

@synthesize target = _target;

- (void)main
{
    @autoreleasepool
    {
        [_target processImage];
    }
}

#if !__has_feature(objc_arc)

- (void)dealloc
{
    [_target release];
    [super dealloc];
}

#endif

@end


@implementation NPImageView

@synthesize asynchronous = _asynchronous;
@synthesize reflectionGap = _reflectionGap;
@synthesize reflectionScale = _reflectionScale;
@synthesize reflectionAlpha = _reflectionAlpha;
@synthesize shadowColor = _shadowColor;
@synthesize shadowOffset = _shadowOffset;
@synthesize shadowBlur = _shadowBlur;
@synthesize cornerRadius = _cornerRadius;
@synthesize customEffectsBlock = _customEffectsBlock;
@synthesize cacheKey = _cacheKey;

@synthesize originalImage = _originalImage;
@synthesize imageView = _imageView;
@synthesize imageContentURL = _imageContentURL;
@synthesize loading = _loading;

#pragma mark -
#pragma mark Shared storage

+ (NSOperationQueue *)processingQueue
{
    static NSOperationQueue *sharedQueue = nil;
    if (sharedQueue == nil)
    {
        sharedQueue = [[NSOperationQueue alloc] init];
        [sharedQueue setMaxConcurrentOperationCount:4];
    }
    return sharedQueue;
}

+ (NSCache *)processedImageCache
{
    static NSCache *sharedCache = nil;
    if (sharedCache == nil)
    {
        sharedCache = [[NSCache alloc] init];
    }
    return sharedCache;
}


#pragma mark -
#pragma mark Setup

- (void)setUp
{
    self.shadowColor = [UIColor blackColor];
    _imageView = [[UIImageView alloc] initWithFrame:self.bounds];
    _imageView.contentMode = UIViewContentModeCenter;
    [self addSubview:_imageView];
   
    _loading = [[UIActivityIndicatorView alloc]init];
    _loading.frame = CGRectMake((_imageView.frame.size.width/2.0)-10.0, (_imageView.frame.size.height/2.0)-10.0, 20.0, 20.0);
    [_loading setHidesWhenStopped:YES];
    [_imageView addSubview:_loading];
   
    [self setImage:super.image];
    super.image = nil;
}

- (id)initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame]))
    {
        [self setUp];
    }
    return self;
}

- (id)initWithImage:(UIImage *)image
{
    if ((self = [super initWithImage:image]))
    {
        [self setUp];
    }
    return self;
}

- (id)initWithImage:(UIImage *)image highlightedImage:(UIImage *)highlightedImage
{
    if ((self = [super initWithImage:image highlightedImage:highlightedImage]))
    {
        [self setUp];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if ((self = [super initWithCoder:aDecoder]))
    {
        [self setUp];
    }
    return self;
}

#if !__has_feature(objc_arc)

- (void)dealloc
{
    [_customEffectsBlock release];
    [_cacheKey release];
    [_originalImage release];
    [_shadowColor release];
    [_imageView release];
    [_imageContentURL release];
    [_loading release];
    [super dealloc];   
}

#endif


#pragma mark -
#pragma mark Caching

- (NSString *)colorHash:(UIColor *)color
{
    NSString *colorString = @"{0.00,0.00}";
    if (color && ![color isEqual:[UIColor clearColor]])
    {
        NSInteger componentCount = CGColorGetNumberOfComponents(color.CGColor);
        const CGFloat *components = CGColorGetComponents(color.CGColor);
        NSMutableArray *parts = [NSMutableArray arrayWithCapacity:componentCount];
        for (int i = 0; i < componentCount; i++)
        {
            [parts addObject:[NSString stringWithFormat:@"%.2f", components[i]]];
        }
        colorString = [NSString stringWithFormat:@"{%@}", [parts componentsJoinedByString:@","]];
    }
    return colorString;
}

- (NSString *)imageHash:(UIImage *)image
{
    static NSInteger hashKey = 1;
    NSString *number = objc_getAssociatedObject(image, @"FXImageHash");
    if (!number && image)
    {
        number = [NSString stringWithFormat:@"%i", hashKey++];
        objc_setAssociatedObject(image, @"FXImageHash", number, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return number;
}

- (NSString *)cacheKey
{
    if (_cacheKey) return _cacheKey;
   
    return [NSString stringWithFormat:@"%@_%@_%.2f_%.2f_%.2f_%@_%@_%.2f_%.2f_%i",
            _imageContentURL ?: [self imageHash:_originalImage],
            NSStringFromCGSize(self.bounds.size),
            _reflectionGap,
            _reflectionScale,
            _reflectionAlpha,
            [self colorHash:_shadowColor],
            NSStringFromCGSize(_shadowOffset),
            _shadowBlur,
            _cornerRadius,
            self.contentMode];
}

- (void)cacheProcessedImage:(UIImage *)processedImage forKey:(NSString *)cacheKey
{
    [[[self class] processedImageCache] setObject:processedImage forKey:cacheKey];
}

- (UIImage *)cachedProcessedImage
{
    return [[[self class] processedImageCache] objectForKey:[self cacheKey]];
}

#pragma mark -
#pragma mark Processing

- (void)setProcessedImageOnMainThread:(NSArray *)array
{
    //get images
    NSString *cacheKey = [array objectAtIndex:1];
    UIImage *processedImage = [array objectAtIndex:0];
    processedImage = ([processedImage isKindOfClass:[NSNull class]])? nil: processedImage;
   
    if (processedImage)
    {
        //cache image
        [self cacheProcessedImage:processedImage forKey:cacheKey];
    }
   
    //set image
    if ([[self cacheKey] isEqualToString:cacheKey])
    {
        //implement crossfade transition without needing to import QuartzCore
        id animation = objc_msgSend(NSClassFromString(@"CATransition"), @selector(animation));
        objc_msgSend(animation, @selector(setType:), @"kCATransitionFade");
        objc_msgSend(self.layer, @selector(addAnimation:forKey:), animation, nil);
       
        //set processed image
        [self willChangeValueForKey:@"processedImage"];
        _imageView.image = processedImage;
        [self didChangeValueForKey:@"processedImage"];
    }
}

- (void)processImage
{
    //get properties
    NSString *cacheKey = [self cacheKey];
    UIImage *image = _originalImage;
    NSURL *imageURL = _imageContentURL;
    CGSize size = self.bounds.size;
    CGFloat reflectionGap = _reflectionGap;
    CGFloat reflectionScale = _reflectionScale;
    CGFloat reflectionAlpha = _reflectionAlpha;
    UIColor *shadowColor = _shadowColor;
    CGSize shadowOffset = _shadowOffset;
    CGFloat shadowBlur = _shadowBlur;
    CGFloat cornerRadius = _cornerRadius;
    UIImage *(^customEffectsBlock)(UIImage *image) = [_customEffectsBlock copy];
    UIViewContentMode contentMode = self.contentMode;
   
#if !__has_feature(objc_arc)

    [[image retain] autorelease];
    [[imageURL retain] autorelease];
    [[shadowColor retain] autorelease];
    [customEffectsBlock autorelease];
   
#endif
   
    //check cache
    UIImage *processedImage = [self cachedProcessedImage];
    if (!processedImage)
    {
        //load image
        if (imageURL)
        {
            NSURLRequest *request = [NSURLRequest requestWithURL:imageURL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30.0];
            [_loading startAnimating];
            NSError *error = nil;
            NSURLResponse *response = nil;
            NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
            if (error)
            {
                NSLog(@"Error loading image for URL: %@, %@", imageURL, error);
                return;
            }
            else
            {
                image = [UIImage imageWithData:data];
                [_loading stopAnimating];
                if ([[[imageURL path] stringByDeletingPathExtension] hasSuffix:@"@2x"])
                {
                    image = [UIImage imageWithCGImage:image.CGImage scale:2.0f orientation:image.imageOrientation];
                }
            }
        }
       
        if (image)
        {
            //crop and scale image
            processedImage = [image imageCroppedAndScaledToSize:size
                                                    contentMode:contentMode
                                                       padToFit:NO];
           
            //apply custom processing
            if (customEffectsBlock)
            {
                processedImage = customEffectsBlock(processedImage);
            }
           
            //clip corners
            if (cornerRadius)
            {
                processedImage = [processedImage imageWithCornerRadius:cornerRadius];
            }
           
            //apply shadow
            if (shadowColor && ![shadowColor isEqual:[UIColor clearColor]] &&
                (shadowBlur || !CGSizeEqualToSize(shadowOffset, CGSizeZero)))
            {
                reflectionGap -= 2.0f * (fabsf(shadowOffset.height) + shadowBlur);
                processedImage = [processedImage imageWithShadowColor:shadowColor
                                                               offset:shadowOffset
                                                                 blur:shadowBlur];
            }
           
            //apply reflection
            if (reflectionScale && reflectionAlpha)
            {
                processedImage = [processedImage imageWithReflectionWithScale:reflectionScale
                                                                          gap:reflectionGap
                                                                        alpha:reflectionAlpha];
            }
        }
    }
   
    //cache and set image
    if ([[NSThread currentThread] isMainThread])
    {
        if (processedImage)
        {
            [self cacheProcessedImage:processedImage forKey:cacheKey];
        }
        [self willChangeValueForKey:@"processedImage"];
        _imageView.image = processedImage;
        [self didChangeValueForKey:@"processedImage"];
    }
    else
    {
        [self performSelectorOnMainThread:@selector(setProcessedImageOnMainThread:)
                               withObject:[NSArray arrayWithObjects:
                                           processedImage ?: [NSNull null],
                                           cacheKey,
                                           nil]
                            waitUntilDone:YES];
    }
}

- (void)queueProcessingOperation:(FXImageOperation *)operation
{
    //suspend operation queue
    NSOperationQueue *queue = [[self class] processingQueue];
    [queue setSuspended:YES];
   
    //check for existing operations
    for (FXImageOperation *op in queue.operations)
    {
        if ([op isKindOfClass:[FXImageOperation class]])
        {
            if (op.target == self && ![op isExecuting])
            {
                //already queued
                [queue setSuspended:NO];
                return;
            }
        }
    }
   
    //make op a dependency of all queued ops
    NSInteger maxOperations = ([queue maxConcurrentOperationCount] > 0) ? [queue maxConcurrentOperationCount]: INT_MAX;
    NSInteger index = [queue operationCount] - maxOperations;
    if (index >= 0)
    {
        NSOperation *op = [[queue operations] objectAtIndex:index];
        if (![op isExecuting])
        {
            [op addDependency:operation];
        }
    }
   
    //add operation to queue
    [queue addOperation:operation];
   
    //resume queue
    [queue setSuspended:NO];
}

- (void)queueImageForProcessing
{
    //create processing operation
    FXImageOperation *operation = [[FXImageOperation alloc] init];
    operation.target = self;
   
    //set operation thread priority
    [operation setThreadPriority:1.0];
   
    //queue operation
    [self queueProcessingOperation:operation];
   
#if !__has_feature(objc_arc)
   
    [operation release];
   
#endif
   
}

- (void)updateProcessedImage
{
    id processedImage = [self cachedProcessedImage];
    if (!processedImage && !_originalImage && !_imageContentURL)
    {
        processedImage = [NSNull null];
    }
    if (processedImage)
    {
        //use cached version
        [self willChangeValueForKey:@"processedImage"];
        _imageView.image = ([processedImage isKindOfClass:[NSNull class]])? nil: processedImage;
        [self didChangeValueForKey:@"processedImage"];
    }
    else if (_asynchronous)
    {
        //process in background
        [self queueImageForProcessing];
    }
    else
    {
        //process on main thread
        [self processImage];
    }
}

- (void)layoutSubviews
{
    _imageView.frame = self.bounds;
    if (_imageContentURL || self.image)
    {
        [self updateProcessedImage];
    }
}


#pragma mark -
#pragma mark Setters and getters

- (UIImage *)processedImage
{
    return _imageView.image;
}

- (void)setProcessedImage:(UIImage *)image
{
    self.imageContentURL = nil;
    [self willChangeValueForKey:@"image"];
    self.originalImage = nil;
    [self didChangeValueForKey:@"image"];
    _imageView.image = image;
}

- (UIImage *)image
{
    return _originalImage;
}

- (void)setImage:(UIImage *)image
{
    if (_imageContentURL || ![image isEqual:_originalImage])
    {       
        //update processed image
        self.imageContentURL = nil;
        self.originalImage = image;
        [self updateProcessedImage];
    }
}

- (void)setReflectionGap:(CGFloat)reflectionGap
{
    if (_reflectionGap != reflectionGap)
    {
        _reflectionGap = reflectionGap;
        [self setNeedsLayout];
    }
}

- (void)setReflectionScale:(CGFloat)reflectionScale
{
    if (_reflectionScale != reflectionScale)
    {
        _reflectionScale = reflectionScale;
        [self setNeedsLayout];
    }
}

- (void)setReflectionAlpha:(CGFloat)reflectionAlpha
{
    if (_reflectionAlpha != reflectionAlpha)
    {
        _reflectionAlpha = reflectionAlpha;
        [self setNeedsLayout];
    }
}

- (void)setShadowColor:(UIColor *)shadowColor
{
    if (![_shadowColor isEqual:shadowColor])
    {
       
#if !__has_feature(objc_arc)
       
        [_shadowColor release];
        _shadowColor = [shadowColor retain];
       
#else
       
        _shadowColor = shadowColor;
       
#endif
       
        [self setNeedsLayout];
    }
}

- (void)setShadowOffset:(CGSize)shadowOffset
{
    if (!CGSizeEqualToSize(_shadowOffset, shadowOffset))
    {
        _shadowOffset = shadowOffset;
        [self setNeedsLayout];
    }
}

- (void)setShadowBlur:(CGFloat)shadowBlur
{
    if (_shadowBlur != shadowBlur)
    {
        _shadowBlur = shadowBlur;
        [self setNeedsLayout];
    }
}

- (void)setContentMode:(UIViewContentMode)contentMode
{
    if (self.contentMode != contentMode)
    {
        super.contentMode = contentMode;
        [self setNeedsLayout];
    }
}

- (void)setCustomEffectsBlock:(UIImage *(^)(UIImage *))customEffectsBlock
{
    if (![customEffectsBlock isEqual:_customEffectsBlock])
    {
        _customEffectsBlock = [customEffectsBlock copy];
        [self setNeedsLayout];
    }
}

- (void)setCacheKey:(NSString *)cacheKey
{
    if (![cacheKey isEqual:_cacheKey])
    {
        _cacheKey = [cacheKey copy];
        [self setNeedsLayout];
    }
}


#pragma mark -
#pragma mark loading

- (void)setImageWithContentsOfFile:(NSString *)file
{
    if ([[file pathExtension] length] == 0)
    {
        file = [file stringByAppendingPathExtension:@"png"];
    }
    if (![file isAbsolutePath])
    {
        file = [[NSBundle mainBundle] pathForResource:file ofType:nil];
    }
    if ([UIScreen mainScreen].scale == 2.0f)
    {
        NSString *temp = [[[file stringByDeletingPathExtension] stringByAppendingString:@"@2x"] stringByAppendingPathExtension:[file pathExtension]];
        if ([[NSFileManager defaultManager] fileExistsAtPath:temp])
        {
            file = temp;
        }
    }
    [self setImageWithContentsOfURL:[NSURL fileURLWithPath:file]];
}

- (void)setImageWithContentsOfURL:(NSURL *)URL
{
    if (![URL isEqual:_imageContentURL])
    {
        //update processed image
        [self willChangeValueForKey:@"image"];
        self.originalImage = nil;
        [self didChangeValueForKey:@"image"];
        self.imageContentURL = URL;
        [self updateProcessedImage];
    }
}

@end

Step 2 : Create two files named as "UIImage+NP.h"  and "UIImage+NP.m" for generating UIImage category.

#import <UIKit/UIKit.h>


@interface UIImage (NP)

- (UIImage *)imageCroppedToRect:(CGRect)rect;
- (UIImage *)imageScaledToSize:(CGSize)size;
- (UIImage *)imageScaledToFitSize:(CGSize)size;
- (UIImage *)imageScaledToFillSize:(CGSize)size;
- (UIImage *)imageCroppedAndScaledToSize:(CGSize)size
                             contentMode:(UIViewContentMode)contentMode
                                padToFit:(BOOL)padToFit;

- (UIImage *)reflectedImageWithScale:(CGFloat)scale;
- (UIImage *)imageWithReflectionWithScale:(CGFloat)scale gap:(CGFloat)gap alpha:(CGFloat)alpha;
- (UIImage *)imageWithShadowColor:(UIColor *)color offset:(CGSize)offset blur:(CGFloat)blur;
- (UIImage *)imageWithCornerRadius:(CGFloat)radius;
- (UIImage *)imageWithAlpha:(CGFloat)alpha;
- (UIImage *)imageWithMask:(UIImage *)maskImage;

- (UIImage *)maskImageFromImageAlpha;


@end


#import "UIImage+NP.h"

@implementation UIImage (NP)

- (UIImage *)imageCroppedToRect:(CGRect)rect
{
    //create drawing context
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0f);
   
    //draw
    [self drawAtPoint:CGPointMake(-rect.origin.x, -rect.origin.y)];
   
    //capture resultant image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
   
    //return image
    return image;
}

- (UIImage *)imageScaledToSize:(CGSize)size
{  
    //avoid redundant drawing
    if (CGSizeEqualToSize(self.size, size))
    {
        return self;
    }
   
    //create drawing context
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
   
    //draw
    [self drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];
   
    //capture resultant image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
   
    //return image
    return image;
}

- (UIImage *)imageScaledToFitSize:(CGSize)size
{
    //calculate rect
    CGFloat aspect = self.size.width / self.size.height;
    if (size.width / aspect <= size.height)
    {
        return [self imageScaledToSize:CGSizeMake(size.width, size.width / aspect)];
    }
    else
    {
        return [self imageScaledToSize:CGSizeMake(size.height * aspect, size.height)];
    }
}

- (UIImage *)imageScaledToFillSize:(CGSize)size
{
    if (CGSizeEqualToSize(self.size, size))
    {
        return self;
    }
    //calculate rect
    CGFloat aspect = self.size.width / self.size.height;
    if (size.width / aspect >= size.height)
    {
        return [self imageScaledToSize:CGSizeMake(size.width, size.width / aspect)];
    }
    else
    {
        return [self imageScaledToSize:CGSizeMake(size.height * aspect, size.height)];
    }
}

- (UIImage *)imageCroppedAndScaledToSize:(CGSize)size
                             contentMode:(UIViewContentMode)contentMode
                                padToFit:(BOOL)padToFit;
{
    //calculate rect
    CGRect rect = CGRectZero;
    switch (contentMode)
    {
        case UIViewContentModeScaleAspectFit:
        {
            CGFloat aspect = self.size.width / self.size.height;
            if (size.width / aspect <= size.height)
            {
                rect = CGRectMake(0.0f, (size.height - size.width / aspect) / 2.0f, size.width, size.width / aspect);
            }
            else
            {
                rect = CGRectMake((size.width - size.height * aspect) / 2.0f, 0.0f, size.height * aspect, size.height);
            }
            break;
        }
        case UIViewContentModeScaleAspectFill:
        {
            CGFloat aspect = self.size.width / self.size.height;
            if (size.width / aspect >= size.height)
            {
                rect = CGRectMake(0.0f, (size.height - size.width / aspect) / 2.0f, size.width, size.width / aspect);
            }
            else
            {
                rect = CGRectMake((size.width - size.height * aspect) / 2.0f, 0.0f, size.height * aspect, size.height);
            }
            break;
        }
        case UIViewContentModeCenter:
        {
            rect = CGRectMake((size.width - self.size.width) / 2.0f, (size.height - self.size.height) / 2.0f, self.size.width, self.size.height);
            break;
        }
        case UIViewContentModeTop:
        {
            rect = CGRectMake((size.width - self.size.width) / 2.0f, 0.0f, self.size.width, self.size.height);
            break;
        }
        case UIViewContentModeBottom:
        {
            rect = CGRectMake((size.width - self.size.width) / 2.0f, size.height - self.size.height, self.size.width, self.size.height);
            break;
        }
        case UIViewContentModeLeft:
        {
            rect = CGRectMake(0.0f, (size.height - self.size.height) / 2.0f, self.size.width, self.size.height);
            break;
        }
        case UIViewContentModeRight:
        {
            rect = CGRectMake(size.width - self.size.width, (size.height - self.size.height) / 2.0f, self.size.width, self.size.height);
            break;
        }
        case UIViewContentModeTopLeft:
        {
            rect = CGRectMake(0.0f, 0.0f, self.size.width, self.size.height);
            break;
        }
        case UIViewContentModeTopRight:
        {
            rect = CGRectMake(size.width - self.size.width, 0.0f, self.size.width, self.size.height);
            break;
        }
        case UIViewContentModeBottomLeft:
        {
            rect = CGRectMake(0.0f, size.height - self.size.height, self.size.width, self.size.height);
            break;
        }
        case UIViewContentModeBottomRight:
        {
            rect = CGRectMake(size.width - self.size.width, size.height - self.size.height, self.size.width, self.size.height);
            break;
        } 
        default:
        {
            rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
            break;
        }
    }
   
    if (!padToFit)
    {
        //remove padding
        if (rect.size.width < size.width)
        {
            size.width = rect.size.width;
            rect.origin.x = 0.0f;
        }
        if (rect.size.height < size.height)
        {
            size.height = rect.size.height;
            rect.origin.y = 0.0f;
        }
    }
   
    //avoid redundant drawing
    if (CGSizeEqualToSize(self.size, size))
    {
        return self;
    }
   
    //create drawing context
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
   
    //draw
    [self drawInRect:rect];
   
    //capture resultant image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
   
    //return image
    return image;
}

+ (CGImageRef)gradientMask
{
    static CGImageRef sharedMask = NULL;
    if (sharedMask == NULL)
    {
        //create gradient mask
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(1, 256), YES, 0.0);
        CGContextRef gradientContext = UIGraphicsGetCurrentContext();
        CGFloat colors[] = {0.0, 1.0, 1.0, 1.0};
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
        CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, colors, NULL, 2);
        CGPoint gradientStartPoint = CGPointMake(0, 0);
        CGPoint gradientEndPoint = CGPointMake(0, 256);
        CGContextDrawLinearGradient(gradientContext, gradient, gradientStartPoint,
                                    gradientEndPoint, kCGGradientDrawsAfterEndLocation);
        sharedMask = CGBitmapContextCreateImage(gradientContext);
        CGGradientRelease(gradient);
        CGColorSpaceRelease(colorSpace);
        UIGraphicsEndImageContext();
    }
    return sharedMask;
}

- (UIImage *)reflectedImageWithScale:(CGFloat)scale
{
    //get reflection dimensions
    CGFloat height = ceil(self.size.height * scale);
    CGSize size = CGSizeMake(self.size.width, height);
    CGRect bounds = CGRectMake(0.0f, 0.0f, size.width, size.height);
   
    //create drawing context
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
   
    //clip to gradient
    CGContextClipToMask(context, bounds, [[self class] gradientMask]);
   
    //draw reflected image
    CGContextScaleCTM(context, 1.0f, -1.0f);
    CGContextTranslateCTM(context, 0.0f, -self.size.height);
    [self drawInRect:CGRectMake(0.0f, 0.0f, self.size.width, self.size.height)];
   
    //capture resultant image
    UIImage *reflection = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
   
    //return reflection image
    return reflection;
}

- (UIImage *)imageWithReflectionWithScale:(CGFloat)scale gap:(CGFloat)gap alpha:(CGFloat)alpha
{
    //get reflected image
    UIImage *reflection = [self reflectedImageWithScale:scale];
    CGFloat reflectionOffset = reflection.size.height + gap;
   
    //create drawing context
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.size.width, self.size.height + reflectionOffset * 2.0f), NO, 0.0f);
   
    //draw reflection
    [reflection drawAtPoint:CGPointMake(0.0f, reflectionOffset + self.size.height + gap) blendMode:kCGBlendModeNormal alpha:alpha];
   
    //draw image
    [self drawAtPoint:CGPointMake(0.0f, reflectionOffset)];
   
    //capture resultant image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
   
    //return image
    return image;
}

- (UIImage *)imageWithShadowColor:(UIColor *)color offset:(CGSize)offset blur:(CGFloat)blur
{
    //get size
    CGSize border = CGSizeMake(fabsf(offset.width) + blur, fabsf(offset.height) + blur);
    CGSize size = CGSizeMake(self.size.width + border.width * 2.0f, self.size.height + border.height * 2.0f);
   
    //create drawing context
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
   
    //set up shadow
    CGContextSetShadowWithColor(context, offset, blur, color.CGColor);
   
    //draw with shadow
    [self drawAtPoint:CGPointMake(border.width, border.height)];
   
    //capture resultant image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
   
    //return image
    return image;
}

- (UIImage *)imageWithCornerRadius:(CGFloat)radius
{
    //create drawing context
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
   
    //clip image
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, 0.0f, radius);
    CGContextAddLineToPoint(context, 0.0f, self.size.height - radius);
    CGContextAddArc(context, radius, self.size.height - radius, radius, M_PI, M_PI / 2.0f, 1);
    CGContextAddLineToPoint(context, self.size.width - radius, self.size.height);
    CGContextAddArc(context, self.size.width - radius, self.size.height - radius, radius, M_PI / 2.0f, 0.0f, 1);
    CGContextAddLineToPoint(context, self.size.width, radius);
    CGContextAddArc(context, self.size.width - radius, radius, radius, 0.0f, -M_PI / 2.0f, 1);
    CGContextAddLineToPoint(context, radius, 0.0f);
    CGContextAddArc(context, radius, radius, radius, -M_PI / 2.0f, M_PI, 1);
    CGContextClip(context);
   
    //draw image
    [self drawAtPoint:CGPointZero];
   
    //capture resultant image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
   
    //return image
    return image;
}

- (UIImage *)imageWithAlpha:(CGFloat)alpha
{
    //create drawing context
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
   
    //draw with alpha
    [self drawAtPoint:CGPointZero blendMode:kCGBlendModeNormal alpha:alpha];
   
    //capture resultant image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
   
    //return image
    return image;
}

- (UIImage *)imageWithMask:(UIImage *)maskImage;
{
    //create drawing context
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
   
    //apply mask
    CGContextClipToMask(context, CGRectMake(0.0f, 0.0f, self.size.width, self.size.height), maskImage.CGImage);
   
    //draw image
    [self drawAtPoint:CGPointZero];
   
    //capture resultant image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
   
    //return image
    return image;
}

- (UIImage *)maskImageFromImageAlpha
{
    //get dimensions
    NSInteger width = CGImageGetWidth(self.CGImage);
    NSInteger height = CGImageGetHeight(self.CGImage);
   
    //create alpha image
    NSInteger bytesPerRow = ((width + 3) / 4) * 4;
    void *data = calloc(bytesPerRow * height, sizeof(unsigned char *));
    CGContextRef context = CGBitmapContextCreate(data, width, height, 8, bytesPerRow, NULL, kCGImageAlphaOnly);
    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), self.CGImage);
   
    //invert alpha pixels
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            NSInteger index = y * bytesPerRow + x;
            ((unsigned char *)data)[index] = 255 - ((unsigned char *)data)[index];
        }
    }
   
    //create mask image
    CGImageRef maskRef = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    UIImage *mask = [UIImage imageWithCGImage:maskRef];
    CGImageRelease(maskRef);
    free(data);

    //return image
    return mask;
}

@end


Step 3 : Now you can use LazyImage view with shadow image by just puting below code into your class file.

        FXImageView *imageView = [[[FXImageView alloc] initWithFrame:CGRectMake(0, 0, BUTTON_WIDTH, BUTTON_HEIGHT)] autorelease];
        imageView.contentMode = UIViewContentModeScaleToFill;
        imageView.asynchronous = YES;
        imageView.reflectionScale = 0.5f;
        imageView.reflectionAlpha = 0.0f;
        imageView.reflectionGap = 10.0f;
        imageView.shadowOffset = CGSizeMake(0.0f, 2.0f);
        imageView.shadowBlur = 5.0f;
        imageView.cornerRadius = 10.0f;
    //set image
    [((FXImageView *)view) setImageWithContentsOfURL:[NSURL URLWithString:@"ImageUrlPath"]];


Enjoy and implement the code.. !!!!!

Regards,
Nilesh M. Prajapati
-->