Friday, 11 March 2016

CAShapeLayer

CAShapeLayer is a specialized subclass of CALayer that draws itself using the shape you define via the path property. path is an instance of CGPath. We could leverage the convenient UIBezierPath APIs to create a path, and then retrieve the CGPath from it. Besides all the animatable properties inherited from CALayer, there are other animatable properties that let you control attributes such as fill color, stroke color, line thickness, etc.


Set rounded corner of a 'UIView' using "CAShapeLayer" 

//First create a instance of UIView
UIView *rectangleView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 300, 300)];

//set background color of UIView
rectangleView.backgroundColor = [UIColor redColor];

//Add subview to main view
[self.view addSubview:rectangleView];

//Create a instance of CAShapeLayer
CAShapeLayer *shapeLayer = [CAShapeLayer layer];

//set path for CAShapeLayer property's 'path'
UIBezierPath *shapePath =[UIBezierPath bezierPathWithRoundedRect:rectangleView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(10, 10)];

//set CAShapeLayer Path
shapeLayer.path = shapePath.CGPath;

//Add CAShapeLayer to subview
rectangleView.layer.mask = shapeLayer;

By using CAShapelayer we can specify radius for particular corners.

//Set  radius of UIView for Top right and bottom left corners only
UIBezierPath *shapePath =[UIBezierPath bezierPathWithRoundedRect:rectangleView.bounds byRoundingCorners:(UIRectCornerTopRight | UIRectCornerBottomLeft) cornerRadii:CGSizeMake(10, 10)];
    shapeLayer.path = shapePath.CGPath;
    rectangleView.layer.mask = shapeLayer;

Friday, 4 March 2016

UIImagePickerController in Swift

UIImagePickerController  class manages customizable, system-supplied user interface for taking pictures and movies, and for choosing saved images and movies for use in the app. A UIImagePickerController manages user interactions and delivers the results of those interactions to a delegate object.
For more details Click here.

To use an image picker controller with in the app, perform these steps:

1) Verify that the device is capable of picking content from the desired source.
2) Check which media types are available for the source type using.
3) Adjust image picker controller's UI according to media type
4) Present user interface.


Code:

// MARK: - Open Camera
    func openCamera(source:UIImagePickerControllerSourceType){


//Check source type available or not
        if(UIImagePickerController.isSourceTypeAvailable(source) == false){
            return;
        }

//Create new object of UIImagePickerContrller
        let imagepickerController = UIImagePickerController()
       imagepickerController.sourceType = source
        imagepickerController.delegate = self

//Present UIImagePickerContrller user interface
        self.presentViewController(imagepickerController, animated: true, completion: nil)
    }


//MARK: - Image Picker Delegate
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        nameTitlelabel.hidden = false
        //dismiss image picker controller view
        picker.dismissViewControllerAnimated(true, completion: nil)
    }


    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

//Get selected image
        let seletctedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        patientImageView.image = seletctedImage

//dismiss image picker controller view
        picker.dismissViewControllerAnimated(true, completion: nil)
    }

Friday, 26 February 2016

UIAlertController in Swift

A UIAlertController object displays an alert message. This class replaces the UIActionSheet and UIAlertView classes.
In addition to displaying a message, associate actions with alert controller to give a way to respond.
Click Here for more details.

//Display UIAlertView
func displayAlert(){
        let alertController = UIAlertController(title: "Alert Message", message: "Welcome to you", preferredStyle: .Alert)
        alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
        presentViewController(alertController, animated: true, completion: nil)
    }


//Add More action with UIAlertController
func alertOkButtonAction(actionTarget: UIAlertAction){
        print("Ok Action Call")
    }

 //create a action
let OkAction = UIAlertAction(title: "Ok", style: .Default, handler: alertOkButtonAction)
alertController.addAction(OkAction)


//Display alert with  UITextField
alertController.addTextFieldWithConfigurationHandler { (nameTxtFld) -> Void in
           nameTxtFld.textColor = UIColor.blueColor()
        }

//We can also add action on UItextField
 func textChange(txtFld:UITextField){
        let str = txtFld.text! as NSString
        print(str)
       
    }

//Add action on UITextField
alertController.addTextFieldWithConfigurationHandler { (nameTxtFld) -> Void in
           nameTxtFld.textColor = UIColor.blueColor()

           nameTxtFld.addTarget(self, action: "textChange:", forControlEvents: .EditingChanged)
        }

Friday, 19 February 2016

Create a Simple Drawing App

A UIBezierPath object combines the geometry of a path with attributes that describe the path during rendering. We can set the geometry and attributes separately and can change them independent of one another. Once we have the object configured the way you want it, you can tell it to draw itself in the current context. Because the creation, configuration, and rendering process are all distinct steps, Bezier path objects can be reused easily in  code. We can even use the same object to render the same shape multiple times, perhaps changing the rendering options between successive drawing calls. 
For more details about UIBezierPath Click Here.

Now, we are going to create a simple drawing app using UIBezierpath.

First, create a  subclass of UIView Class.
Suppose name is SketchView
 Inside SketchView.h
@interface SketchView : UIView
{
    UIBezierPath *scriblePath;
}


Add following code in SketchView.m

@implementation SketchView

-(instancetype) initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        scriblePath = [[UIBezierPath alloc] init];
        scriblePath.lineCapStyle=kCGLineCapRound;
        scriblePath.miterLimit=0;
        scriblePath.lineWidth = 2; //Set Stroke with
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    [[UIColor blackColor] setStroke];
    [scriblePath strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
}

#pragma mark -
-(void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
     CGPoint touchPoint = [[touches anyObject] locationInView:self.superview];
    [scriblePath moveToPoint:touchPoint];
}
-(void) touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
     CGPoint touchPoint = [[touches anyObject] locationInView:self.superview];
    [scriblePath addLineToPoint:touchPoint];
    [self setNeedsDisplay];
}

@end

 

Friday, 12 February 2016

Add PCH file in Xcode6


In the C and C++ programming languages, a header file is a file whose text may be automatically included in another source file by the C preprocessor, usually specified by the use of compiler directives in the source file.

Prefix.pch is a precompiled header file. Precompiled headers were invented to make compiling faster. Rather than parsing the same header files over and over, these files get parsed once, ahead of time.
Xcode 5 and older version of Xcode by default add PCH file with project, but Xcode 6 doesn't include PCH file automatocally.
We can add PCH file in Project.
Here steps to add PCH file in Project:

1) Create new file by selecting File > New File > iOS > Other > PCH File > Next.
2) Give name to newly created file.(Ex- PrefixHeader)
3) Select Project > Targets > Build Setting.
4) Search for 'Prefix header'.
5) Under "Apple LLVM 7.0" you will get the Prefix Header Key.

 6) Type file directory. (Ex- ProjectFolder/ProjeectName-Prefix.pch).
7) Clean project.
8) Build project.

Friday, 22 January 2016

Draw Custom View With Transparent Oval

UIBezierPath define a path consisting of straight and curved line segment and render the path in custom views. We can use this for specify the geometry of path, path can define simple shapes such as rectangle, oval, arc or can define complex polygons.For more details about UIBezierPath Click Here.

I am going to draw a custom view with transparent oval.I will use UIBenzierPath  fro achieving result.

First create a SubClass of UIView.
Ex. named sub class to CustomView
Inside drawRect: method of CustomView.m

- (void)drawRect:(CGRect)rect {
    // Drawing code

//First Create path for Oval
    UIBezierPath *apath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(5, 5,  self.frame.size.width-10, self.frame.size.height-10)];
    //Create another path
    UIBezierPath *clipPath = [ UIBezierPath bezierPathWithRect:CGRectInfinite];

//Append both path
    [clipPath appendPath:apath];
    clipPath.usesEvenOddFillRule = YES; //

usesEvenOddFillRule property is used to determine whether the even-odd or non-zero rule is used to determine the area enclosed by the path.   

  CGContextSaveGState(UIGraphicsGetCurrentContext());
    [clipPath addClip];
    CGContextSaveGState(UIGraphicsGetCurrentContext());
    [[UIColor orangeColor] setFill];
    [[UIColor blackColor] setStroke];
    clipPath.lineWidth = 2;
    [clipPath stroke];
    [clipPath fill];
}

Friday, 18 December 2015

Math functions in Objective C

Objective C uses c' s math functions which can find in "math.h".
Here, list of some functions which frequently use in code:

1) pow: power of
double pow(double, double)
Ex:  double value = pow (5, 2);   // value = 25
       double value = pow (2, 5);   // value = 32

2) sqrt : square root
double sqrt(double);
Ex: double value = sqrt(16);     // value = 4;

3) ceil : if argument have any decimal value return next integer value(as a double)
 double ceil(double);
Ex: double value = ceil(2.0320);    // value = 3;
      double value = ceil(2.000);    // value = 2;

4) floor :  discard decimal part of argument.
 double floor(double);
Ex: double value = floor(1.98989);    value = 1;

5) round : Round the argument. if a argument have decimal value greater than or equals to  0.5 than return next integer value, and if  decimal value less than 0.5 than return integer part.
 double round(double);
Ex: double value = round(4.5);   //value = 5;
      double value = round(4.4);   //value = 4;

6)fmin : return smallest argument.
   double fmin(double, double);
  Ex: double value = fmin(3, 6);      //value = 3;

7)fmax : return bigger argument.
 double fmax(double, double);
 Ex: double value = fmax(3, 6);     //value = 6;

8)fabs : return absolute value of argument.
 double fabs(double);
 Ex: double value = fabs(10);      // value = 10;
       double value = fabs(-10);      // value = 10;

For more details check ''math.h".