Showing posts with label Customview. Show all posts
Showing posts with label Customview. Show all posts

Sunday, 9 April 2017

Draw a Dashed Pattern Stroke

A small small changes left better impact on UI. In this post we will work on to enhance UI implementation with dashed pattern border on UIView.

Draw dashed pattern border on UIView is very simple and we can use UIBezierPath for draw dashed pattern border.
Lets start, first create subclass of UIView(named DashedBorderView).

#import <UIKit/UIKit.h>

@interface DashedPatternView : UIView

@end


#import "DashedPatternView.h"

@implementation DashedPatternView


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/


@end

Go to DashedPatternView.m and uncomment drawRect: method
Now add following code for draw  a rectangle

- (void)drawRect:(CGRect)rect {
    // Drawing code
    [[UIColor blackColor] setStroke];
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(10, 10)];
    [path addLineToPoint:CGPointMake(rect.size.width, 10)];
    [path addLineToPoint:CGPointMake(rect.size.width, rect.size.height - 10)];
    [path addLineToPoint:CGPointMake(10, rect.size.height - 10)];
    [path closePath];
    path.lineWidth = 2.0;
    [path stroke];
}

 
Go to your controller class and add DashedPatternView as a subview on main view.
Here code

-(void) addBorderView{
DashedPatternView *dashedView = [[DashedPatternView alloc] init];
    dashedView.frame = CGRectMake(100, 300, self.view.frame.size.width-200, 60);
    dashedView.backgroundColor = [UIColor clearColor];
[self.view addSubview:dashedView];

}

Call addBorderView() method from viewDidLoad() method.
Run the app and you can see a rectangle with solid black border
Now we are going to add dashed pattern border instead of solid border
Add following code just before to call stroke method

CGFloat dashes[] = { 6,6,6};
    [path setLineDash:dashes count:3 phase:0];


above two lines of code enough for draw dashed pattern border.
first we have initialize an array for the dashed border style pattern(you can change the pattern and can see result)
second line of code  set pattern for draw with 3 count(Count of pattern array).

Now run the app and you can see a rectangle with dashed pattern border.


Saturday, 17 September 2016

Blure Effect

Adding blur effect on the view's corner

User interface play an important role in development of a good application. With the useful and important features, it is necessity of a application to make a attractive and good looking user interface. A well design interface force user to play with application and enjoy the application for a time being.

A small small effect can make the interface better like presenting sub-view  with animation or bounce, adding blur effect in the corner of sub-views.
Here i am going to add blur effect in the corner of sub views.
We can achieve blur effect by using gradient. We are having in-build CAGraientLayer in iOS, so its not a tough  to add blur effect in both corner of a view, because of this CAGraientLayer.
Click here for details of CAGraientLayer.

First create a project and add a UIView as a subview of view in the storyboard or xib file.
Than go to .h file and create a outlet for added UIView.

@property (nonatomic, weak) IBOutlet UIView *horizontalLineViewFirst;

again go to storyboard  or xib file and connect the outlet to added UIView.

Now switch to .m file and add a method

#pragma mark - Add Gradient
-(void) addGrandientlayerToView:(UIView *)gradientView{
    //create a gradient layer
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    //set gradient color
    CGColorRef outerColor = [[UIColor colorWithWhite:0.97 alpha:1.0] CGColor];
    CGColorRef innerColor = [[UIColor colorWithWhite:0.72 alpha:0.0] CGColor];

    //set name of the layer
    gradientLayer.name = @"BlurGradientLayer";
    //set color to gradien layer
    gradientLayer.colors = [NSArray arrayWithObjects:(__bridge id)outerColor,(__bridge id)innerColor,(__bridge id)innerColor,(__bridge id)outerColor, nil];
    //set location to each color
    gradientLayer.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0],[NSNumber numberWithFloat:0.200],[NSNumber numberWithFloat:0.710],[NSNumber numberWithFloat:1.0], nil];
    //set start point for draw a gradient layer
    [gradientLayer setStartPoint:CGPointMake(0, 0.6)];
    //set start point for draw a gradient layer
    [gradientLayer setEndPoint:CGPointMake(1, 0.6)];
    //set bound of the layer
    gradientLayer.bounds = gradientView.bounds;
    //set anchor point of layer to {0,0}
    gradientLayer.anchorPoint = CGPointZero;
    [gradientView.layer addSublayer:gradientLayer];

}


pass the message to above method form viewDidLoad method

[self addGrandientlayerToView:self.horizontalLineViewFirst];

Run the  app,  we can see a blur effect on added subview.





 
We can see a effect similar to above image a horizontal line with blur corners.

Now rotate the simulator or device,  one side of blur effect get misplace,its come in the middle not in both corners. Lets fix the issue

add another method to reset gradient location after orientation

#pragma mark -
#pragma mark Handle Orientation

- (void) handleOrientationChange:(NSNotification *)notification{
    [self resetAllGradientLayer];
}
-(void) resetAllGradientLayer{
    [self resetGradientforView:self.horizontalLineViewFirst];
}
-(void) resetGradientforView:(UIView *)gradientView{
    for (CAGradientLayer *layer in gradientView.layer.sublayers){
        if ([layer.name isEqualToString:@"BlurGradientLayer"]) {
            layer.bounds = gradientView.bounds;
        }
    }
}

 
Add orientation change notification to controller

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleOrientationChange:) name:UIDeviceOrientationDidChangeNotification object:nil];

 
Now again run the application and check.
Click here for complete project.

Saturday, 30 July 2016

Drawing on iOS



Drawing with Quartz and UIKit:

Quartz is the native drawing technology in iOS. Core Graphics framework is at the heart of Quartz and is the primary interface use for drawing content. Quartz 2D is a two-dimensional drawing engine which is use of such as path based drawing,  painting with transparency, shading, drawing shadows, transparency layers, color management, anti aliased rendering, PDF documents generation, and PDF metadata access.

Configuring the Graphics Context:
View object create a graphics context and sets it as the current context. This context exists only for the the lifetime of the drawRect: call. For retrieve a pointer to this graphics context we can call UIGraphicsGetCurrentContext function. This function returns a reference to a CGContextRef type, which pass to core graphics function to modify the current graphics state. The graphics context contains a stack for save graphics states. When Quartz creates a graphics context, the stack is empty. Using CGContextSaveState function pushes a copy of the current graphics state onto the stack. Modification make to graphics state affect subsequent drawing operations but do not affect the copy stored on the slack.with done of modification we can return to the previous graphics state by popping the saved state off the top of the stack using the CGContextRestoreGState function. Pushing and popping graphics states in this manner is a fast way to return to a previous state.For Details Click here


Drawing:
//Draw a line
In order to draw graphics on the view it is necessary to subclass to create a subclass of UIView and override the drawRect: method.

Lets subclass a UIView(named LineView)

Now override drawRect: method

- (void)drawRect:(CGRect)rect {
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext(); //Get current graphics context
    CGContextSaveGState(context); //Save current context
    CGContextSetLineWidth(context, lineWidth); // set stroke width of line
    CGContextSetStrokeColorWithColor(context, [[UIColor redColor] CGColor]); //set stroke color
    CGContextMoveToPoint(context, 10,  10); // It is the first point of line
    CGContextAddLineToPoint(context, self.bounds.size.width - 10, 10); // set another point of line
    CGContextStrokePath(context); // stroke line
    CGContextRestoreGState(context);
}
Import newly added subclass to ViewController and add as a subview to the ViewController's view.


//Draw a Rectangle
subclass a UIView(named LineView)
and override drawRect: method

- (void)drawRect:(CGRect)rect {
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGContextSetLineWidth(context, lineWidth);
    CGContextSetStrokeColorWithColor(context, [[UIColor redColor] CGColor]);
    CGContextMoveToPoint(context, 10,  10); // start point
    CGContextAddLineToPoint(context, self.bounds.size.width - 10, 10);
    CGContextAddLineToPoint(context, self.bounds.size.width - 10, self.bounds.size.height - 10);
    CGContextAddLineToPoint(context,  10, self.bounds.size.height - 10);
    CGContextAddLineToPoint(context, 10, 10);
    CGContextStrokePath(context);
   CGContextRestoreGState(context);
}

Saturday, 16 July 2016

Custom Input View For System Keyboard



ios allows apps to display custom input views for the system keyboard. It also enables apps to have an accessory view above the system keyboard or custom input view. Additionally, it enables apps to play key-click sounds when users tap on a controls of an input view or input accessory view.
We can display UIPicker, Color Picker and any other custom view instead of system keyboard. I am going to display a UIPickerView for a keyboard.

Here a sample code for display custom input view for the system keyboard.

First create a sub class of UIView, (named "CustomFontSelectionView").

#import <UIKit/UIKit.h>
@interface CustomFontSelectionView : UIView

#import "CustomFontSelectionView.h"
@implementation CustomFontSelectionView


 Now add a UIPicker of Subview, 
 first declare a instance of UIPicker class in file CustomFontSelectionView.h  file
 and a Array  for containing all objects.

@interface CustomFontSelectionView : UIView<UIPickerViewDelegate, UIPickerViewDataSource>
{
    UIPickerView *pickerView;
    NSArray *fontListArray;
}


add below code in  CustomFontSelectionView.m

-(instancetype) initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self initialize];
    }
    return self;
}
-(void) initialize{
    fontListArray = @[[NSNumber numberWithInteger:10],[NSNumber numberWithInteger:11],[NSNumber numberWithInteger:12],[NSNumber numberWithInteger:13],[NSNumber numberWithInteger:14],[NSNumber numberWithInteger:15],[NSNumber numberWithInteger:16],[NSNumber numberWithInteger:17],[NSNumber numberWithInteger:18],[NSNumber numberWithInteger:19],[NSNumber numberWithInteger:20],[NSNumber numberWithInteger:21],[NSNumber numberWithInteger:22],[NSNumber numberWithInteger:23],[NSNumber numberWithInteger:24],[NSNumber numberWithInteger:25]];
    pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    pickerView.delegate = self;
    pickerView.dataSource = self;
    [self addSubview
:pickerView];
}

#pragma mark -
#pragma mark Picker View DataSource
-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return fontListArray.count;
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
#pragma mark Picker View Delegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [NSString stringWithFormat:@"%@",[fontListArray objectAtIndex:row]];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    //send delegate to update text with selected font size
    if (self.fontDelegate && [self.fontDelegate respondsToSelector:@selector(didSelectFontSize:)]) {
        [self.fontDelegate didSelectFontSize:[fontListArray objectAtIndex:row]];
    }
} 




Now import Newly created Class to ViewController class
#import "CustomFontSelectionView.h"

and declare a instance variable for Class object
CustomFontSelectionView *customFontSelectionView; (a variable or instance always declare inside Interface Section)

Now go to ViewController and add a UITextField(either by code or by Xib, we can use any way).
and declare a instance of UITextField inside ViewController.h class.
In case of adding a UITextField using Xib connect IBoutlet with declared UITextField.


Add UITextField by code 
Declare a UItextField instance in ".h" file (named textField).
  
@property (nonatomic, strong)  UITextField *textField;

In ViewController.h
 Add following  code to ".m" file
Inside viewDidload method add code for display  Custom view.
self.textField = [[UITextFiled alloc]initWithFrame:CGRectMake(0, 0, self.view.bound.size.frame, 150)];
 [self.view addSubView: self.textField];

Now initialize Custom View

#pragma mark -
-(void) displayFontSelectionView{
    [self.textField resignFirstResponder];
    if (!customFontSelectionView) {
        customFontSelectionView = [[CustomFontSelectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, height)];
    }
    customFontSelectionView.fontDelegate = self;
    self.textField.inputView = customFontSelectionView;
    [self.textField becomeFirstResponder];
}


Add following piece of code just below  " [self.view addSubView: self.textField];"

self.textField.inputView = customColorSelectionView;

We can also add a Input Accessory view with a keyboard(Appear just above keyboard) in the same way
Add a UIToolbar either using Xib or code and add as a input accessory view.

self.textField..inputAccessoryView = self.toolBar; 


Click here for complete project.