Pages

Thursday 15 December 2016

Add inverted circle overlay to map view

Drawing circle in MKMapView as we see in reminders in iPhone. Here have pasted some code which works as below.


Reference
http://stackoverflow.com/a/31050127


I used class names are below

1. MyMapOverlay.h
2. MyMapOverlayRenderer.h
3. ViewController.h


MyMapOverlay.h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

@interface MyMapOverlay : NSObject<MKOverlay>
- (instancetype)initWithCoordinate:(CLLocationCoordinate2D)coordinate;
@end


MyMapOverlay.m

#import "MyMapOverlay.h"

@implementation MyMapOverlay
@synthesize coordinate = _coordinate;

- (instancetype)initWithCoordinate:(CLLocationCoordinate2D)coordinate {
    self = [super init];
    if (self) {
        _coordinate = coordinate;
    }
    return self;
}

- (MKMapRect)boundingMapRect {
    return MKMapRectWorld;
}

@end


MyMapOverlayRenderer.h

#import <MapKit/MapKit.h>

@interface MyMapOverlayRenderer : MKOverlayRenderer
@property (nonatomic, assign) double diameterInMeters;
@property (nonatomic, assign) MKMapRect circleRect;
@property (nonatomic, copy) UIColor *fillColor;
@end


MyMapOverlayRenderer.m

#import "MyMapOverlayRenderer.h"


@implementation MyMapOverlayRenderer

/// this method is called as a part of rendering the map, and it draws the overlay polygon by polygon
/// which means that it renders overlay by square pieces
- (void)drawMapRect:(MKMapRect)mapRect
          zoomScale:(MKZoomScale)zoomScale
          inContext:(CGContextRef)context {
    
    /// main path - whole area
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(mapRect.origin.x, mapRect.origin.y, mapRect.size.width, mapRect.size.height)];
    
    /// converting to the 'world' coordinates
    double radiusInMapPoints = self.diameterInMeters * MKMapPointsPerMeterAtLatitude(self.overlay.coordinate.latitude);
    MKMapSize radiusSquared = {radiusInMapPoints, radiusInMapPoints};
    MKMapPoint regionOrigin = MKMapPointForCoordinate(self.overlay.coordinate);
    MKMapRect regionRect = (MKMapRect){regionOrigin, radiusSquared}; //origin is the top-left corner
    regionRect = MKMapRectOffset(regionRect, -radiusInMapPoints/2, -radiusInMapPoints/2);
    // clamp the rect to be within the world
    regionRect = MKMapRectIntersection(regionRect, MKMapRectWorld);
    
    /// next path is used for excluding the area within the specific radius from current user location, so it will not be /filled by overlay fill color
    UIBezierPath *excludePath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(_circleRect.origin.x, _circleRect.origin.y, _circleRect.size.width, _circleRect.size.height) cornerRadius:_circleRect.size.width];
    [path appendPath:excludePath];
    
    /// setting overlay fill color
    CGContextSetFillColorWithColor(context, self.fillColor.CGColor);
    /// adding main path. NOTE that exclusionPath was appended to main path, so we should only add 'path'
    CGContextAddPath(context, path.CGPath);
    /// tells the context to fill the path but with regards to even odd rule
    CGContextEOFillPath(context);
}

@end

ViewController.h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

@interface ViewController : UIViewController<MKMapViewDelegate>

@property(nonatomic,weak)IBOutlet MKMapView *map;

@end

ViewController.m

#import "ViewController.h"
#import "MKMapView+ZoomLevel.h"
#import "MyMapOverlay.h"
#import "MyMapOverlayRenderer.h"


@interface ViewController ()
{
    MKCircle *circle,*circle2;
}
@end

@implementation ViewController
@synthesize map;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    map.delegate=self;
    
    
    
    [self centerMap];
}

-(void)centerMap

{
    
    CLLocationCoordinate2D center;
    
    center.latitude = 12.8421;
    center.longitude = 77.6631;
    
    double retVal=1609.344f;
   
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(center,10000 ,10000);
    
    [map setRegion:[map regionThatFits:region] animated:YES];
    
    
    CLLocationDistance fenceDistance = retVal;
    
    CLLocationCoordinate2D circleMiddlePoint = CLLocationCoordinate2DMake(center.latitude, center.longitude);
    
    circle = [MKCircle circleWithCenterCoordinate:circleMiddlePoint radius:fenceDistance];
    
    [map addOverlay: circle];
    
    MyMapOverlay *overlay = [[MyMapOverlay alloc] initWithCoordinate:center];
    [self.map addOverlay:overlay level:MKOverlayLevelAboveLabels];
    

}


-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    NSLog(@"zoom level =%f",[map getZoomLevel]);
    
    CLLocationCoordinate2D center;
    
    center.latitude = 12.8421;
    center.longitude = 77.6631;
    
    if([map getZoomLevel]>30)
    {
         [mapView setCenterCoordinate:center zoomLevel:15 animated:NO];
    }
    
}

- (MKCircleRenderer *)mapView:(MKMapView *)map viewForOverlay:(id <MKOverlay>)overlay
{
   if ([overlay isKindOfClass:[MyMapOverlay class]]) {
        MyMapOverlayRenderer *renderer = [[MyMapOverlayRenderer alloc] initWithOverlay:overlay];
        renderer.fillColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];/// specify color which you want to use for gray out everything out of radius
        renderer.circleRect=circle.boundingMapRect;
       
        return (MKCircleRenderer *)renderer;
    }
    

    
    
    MKCircleRenderer *circleView = [[MKCircleRenderer alloc] initWithOverlay:overlay];
    circleView.strokeColor = [UIColor yellowColor];
    circleView.lineWidth=2.0;
    
    
    return circleView;
}


-(IBAction)btnPlusClick:(id)sender
{
    MKCoordinateRegion region;
    MKCoordinateSpan span;
    region.center.latitude = map.region.center.latitude;
    region.center.longitude = map.region.center.longitude;
    span.latitudeDelta=map.region.span.latitudeDelta /2.0002;
    span.longitudeDelta=map.region.span.longitudeDelta /2.0002;
    region.span=span;
    [map setRegion:region animated:TRUE];
}

-(IBAction)btnMinusClick:(id)sender
{
    MKCoordinateRegion region;
    MKCoordinateSpan span;
    region.center.latitude = map.region.center.latitude;
    region.center.longitude = map.region.center.longitude;
    span.latitudeDelta=map.region.span.latitudeDelta *2.0002;
    span.longitudeDelta=map.region.span.longitudeDelta *2.0002;
    region.span=span;
    [map setRegion:region animated:TRUE];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end


Tuesday 13 October 2015

Image Handling in IOS

I found good blog for image handling in IOS. It is good and they explained well. Please refer the link.

http://blogs.innovationm.com/image-handling-in-ios/

Sunday 27 September 2015

Definitions

Framwork
          A framework is a collection of resources; it collects a static library and its header files into a single structure that Xcode can easily incorporate into your projects.

Tuesday 22 September 2015

Resize image

CGRect rect = CGRectMake(0,0,75,75);
    UIGraphicsBeginImageContext( rect.size );
    [image drawInRect:rect];
    UIImage *picture1 = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    NSData *imageData = UIImagePNGRepresentation(picture1);
    UIImage *img=[UIImage imageWithData:imageData];

Sunday 27 July 2014

ios: Rating Star


Introduction

This post contains a coding that describes the displaying of the static rating star. It is very simple but very effective.

Required Concept(s)
  1. CALayer
  2. UIView
Required Source(s)
  1. An Image with five stars like this




Source Code


 #define POINT             1.0
 #define WIDTH            82.5
 #define HEIGHT          15.0 
 #define DIVISOR         5.0 
 
 //Creation of Rating Star.

 CALayer *mainStar=[CALayer layer]; 
 mainStar.contents=(__bridge id)([UIImage imageNamed:@"rating_star"].CGImage);
 mainStar.frame=CGRectMake(POINT
,POINT,WIDTH,HEIGHT);
 CALayer *starColor=[CALayer layer];
 starColor.backgroundColor=[UIColor blueColor].CGColor;
 starColor.frame=
CGRectMake(0,0,
(3.5/DIVISOR)*WIDTH,HEIGHT);   
 //Change value of 3.5 from 0.0 to 5.0 to see the different rating.
[mainStar addSublayer:starColor];
CALayer *maskStar=[CALayer layer];
maskStar.contents=(__bridge id)([UIImage imageNamed:@"rating_star"].CGImage);
maskStar.frame=CGRectMake(0,0,WIDTH,HEIGHT);  
[mainStar addSublayer:maskStar];
 starColor.mask=maskStar; 
  
// Add Main Star to View
UIView *ratingView=[[UIView alloc] init];
ratingView.frame=CGRectMake(100,100,85,18);
[ratingView.layer addSubLayer:mainStar];
[self.view addSubView:ratingView];   // self may be any view controller.
  

Note
   Mask property of CALayer plays vital role.

Request
    Please post your comments and questions.


Wednesday 12 March 2014

Toast in IOS7 as in Android

Just You can use the following code with uilabel and uianimation to get toast like in android.
It does two works one is toast task and it increases the height of the label according to the text length with wordwrap IOS 7 later

    CGRect initialFrame = CGRectMake(20, self.view.frame.size.height/2,300, 40);
  
   
    NSString *message=@"Toast in Iphone as in Android";
    UILabel *flashLabel=[[UILabel alloc] initWithFrame:initialFrame];
    flashLabel.font=[UIFont fontWithName:@"Optima-Italic" size:12.0];
    flashLabel.backgroundColor=[UIColor whiteColor];
    flashLabel.layer.cornerRadius=3.0f;
    flashLabel.numberOfLines=0;
    flashLabel.textAlignment=NSTextAlignmentCenter;
   
    CGSize maxSize = CGSizeMake(flashLabel.frame.size.width, MAXFLOAT);
   
    CGRect labelRect = [message boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:flashLabel.font} context:nil];
   
    //adjust the label the the new height.
    CGRect newFrame = flashLabel.frame;
    newFrame.size.height = labelRect.size.height;
    flashLabel.frame = newFrame;
    flashLabel.text=message;
    [self.view addSubview:flashLabel];
   
    flashLabel.alpha=1.0;
    self.view.userInteractionEnabled=FALSE;
   
    [UIView animateWithDuration:13.0 animations:^
    {
        flashLabel.alpha=0.0f;
    }
    completion:^(BOOL finished)
    {
        self.view.userInteractionEnabled=TRUE;
       
        [flashLabel removeFromSuperview];
    }];

Sunday 12 January 2014

iPhone: Dynamic Resizable UILabel and UITableViewCell


Dear friends, I am very glad to post this simple concept of uilabel resizing depending on text size with uitableview. This is my first post on blog. I believe, uilabel resizing with uitableview will be helpful to many beginners.

Kindly follow steps involved for uilabel resizing with uitableview.

Step 1: Create project by selecting Single View Application with story board from Xcode.

Step 2: Place UITableViewController on story board from object library.

Step 3:Select UITableViewCell on UITableViewController.

Step 4:Change UITableViewCell Style->Custom, set UITableViewCell Identifier->Cell

Step 5:Place UILableView On UITableViewCell.

Step 6: Create New File Name the Class as "SampleCell" and choose SubClass "UITableViewCell" in the Attributes Inspector.

Step 7: Copy and Paste bellow codes to SampleCell.h and SampleCell.m files.

SampleCell.h

#import <UIKit/UIKit.h>

@interface SampleCell : UITableViewCell
{
    IBOutlet UILabel *testLabel;
}

@property(retain,nonatomic)UILabel *testLabel;

@end

SampleCell.m


#import "SampleCell.h"

@implementation SampleCell

@synthesize testLabel;


- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end

Step 8: Now change the UITableViewCell class to "SampleCell" in the Identity Inspector.
Step 9: Link the UILabel with "testLabel" by referring outlet in the Connection Inspector.

Step 10: Create New File Name the Class as "SampleTable" and choose SubClass "UITableViewController" in the Attributes Inspector.
Step 11: Copy and Paste bellow codes to SampleTable.h and SampleTable.m files.

SampleTable.h


#import <UIKit/UIKit.h>

@interface SampleTable : UITableViewController

@end


SampleTable.m

#import "SampleTable.h"
#import "SampleCell.h"

@interface SampleTable ()

@end

@implementation SampleTable

int a=0;
NSString *test=@"My question essentially boils down to the best way to support dynamic heights of UILabel's (and I suppose other elements) in a UITableCell, and also correctly resize the label width/height and cell heights when rotating. ";

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

   
    // This is used to notify the rotation of the device.

  [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
   
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didRotate:)
                                                 name:@"UIDeviceOrientationDidChangeNotification" object:nil];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    static NSString *CellIdentifier = @"Cell";
    SampleCell *cell =(SampleCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell.testLabel.text=test;
    if ([self isPortrait]) {
       
        cell.testLabel.frame=CGRectMake(10,0,cell.frame.size.width,cell.frame.size.height);
    }
    else
   
   cell.testLabel.frame=CGRectMake(10,0,[[UIScreen mainScreen] bounds].size.height
10,cell.frame.size.height);
 
   cell.testLabel.numberOfLines=0;
   [cell.testLabel sizeToFit];

   return cell;
}
- (void) didRotate:(NSNotification *)notification
{
    [self.tableView reloadData];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   
   
    SampleCell *cell = (SampleCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    //Set the maximum size
    CGSize maximumLabelSize = cell.testLabel.frame.size;
    //Calculate the new size based on the text
    CGSize expectedLabelSize = [test sizeWithFont:cell.testLabel.font constrainedToSize:maximumLabelSize lineBreakMode:cell.testLabel.lineBreakMode];

    return expectedLabelSize.height;
}

-(BOOL)isPortrait
{
    UIInterfaceOrientation orientation=[[UIApplication sharedApplication] statusBarOrientation];
   
    if(orientation==UIInterfaceOrientationPortrait ||
orientation==UIInterfaceOrientationPortraitUpsideDown)return YES;
    return NO;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
@end

Step 12: Now change the UITableViewController class to "SampleTable" in the Identity Inspector.

Step 13: Run and Enjoy.