Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Core Graphics Concept

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 460
    Comment on it

     

    Hi readers!

    This blog includes an example of core graphics with multiple choice option available to the user to draw different shapes in an application. Different shapes which we are going to draw in this application are line, sphere, shadow of oval and gradient effect. First of all we have to build a subclass of UIView and than we will override the drawRect method which helps in making these kind of shapes in an application. We have to take an UIView in user interface and simultaneously one textfield also in which we will provide a list of option with the help of picker. Below is the screenshot of storyboard in which UIView, textfield and a label are taken :-

     

     

     

     

    After creating the user interface now we will move towards the coding part of the same. Subclass of UIView can be created by taking superclass as UIView. Within the subclass we will use switch case to provide option to the user and what ever option user will choose according to that output will be shown.
     


     

    SubClassOfView.h
    
    #import <UIKit/UIKit.h>
    
    @interface SubClassOfView : UIView
    - (void)draw:(NSString*)option; //function in which switch case is used according to users choice.
    @property (nonatomic,strong) NSString *option; //string which
    pass user choice option towards the subclass.
    @end
    
    
    //  SubClassOfView.m
    
    #import "SubClassOfView.h"
    
    @implementation SubClassOfView
    
    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
     */
    
    - (void)drawRect:(CGRect)rect {
        
        // Drawing code
        [self draw:self.option]; //here we are calling method with string send by the user
    }
    
    
    - (void)draw:(NSString*)option {
    
        NSArray *items = @[@"Line", @"Sphere",@"Shadow Of Circle",@"Gradient Effect"];
        int item = [items indexOfObject:option];
        
        switch (item) {
            case 0:
                [self line];
                break;
            case 1:
                [self Sphere];
                break;
            case 2:
                [self shadowOval];
                break;
            case 3:
                [self gradient];
                break;
            default:
                NSLog(@"Please select your choice");
                break;
        }
    }
    
    -(void)line{
    
    //code to draw a line
    
            CGContextRef context = UIGraphicsGetCurrentContext();
            CGContextSetLineWidth(context, 2.0);
            CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
            CGFloat components[] = {0.0, 0.0, 1.0, 1.0};
            CGColorRef color = CGColorCreate(colorspace, components);
            CGContextSetStrokeColorWithColor(context, color);
            CGContextMoveToPoint(context, 50, 90);
            CGContextAddLineToPoint(context, 400, 400);
            CGContextStrokePath(context);
            CGColorSpaceRelease(colorspace);
           // CGColorRelease(color);
    }
    
    -(void)Sphere
    {
    //code to draw sphere
    
            CGContextRef context = UIGraphicsGetCurrentContext();
            CGGradientRef gradient;
            CGColorSpaceRef colorspace;
            CGFloat locations[2] = { 0.0, 1.0};
        
            NSArray *colors = @[(id)[UIColor whiteColor].CGColor,
                                (id)[UIColor redColor].CGColor];
        
            colorspace = CGColorSpaceCreateDeviceRGB();
        
            gradient = CGGradientCreateWithColors(colorspace,
                                                  (CFArrayRef)colors, locations);
        
            CGPoint startPoint, endPoint;
            CGFloat startRadius, endRadius;
            startPoint.x = 180;
            startPoint.y = 180;
            endPoint.x = 210;
            endPoint.y = 250;
            startRadius = 0;
            endRadius = 75;
        
            CGContextDrawRadialGradient (context, gradient, startPoint,
                                         startRadius, endPoint, endRadius,
                                         0);
    }
    
    -(void)shadowOval
    {
    //code to draw shadow of oval shape
    
            CGContextRef context = UIGraphicsGetCurrentContext();
        
            CGSize  myShadowOffset = CGSizeMake (-10,  15);
        
            CGContextSaveGState(context);
        
            CGContextSetShadow (context, myShadowOffset, 5);
        
            CGContextSetLineWidth(context, 4.0);
            CGContextSetStrokeColorWithColor(context,
                                             [UIColor redColor].CGColor);
            CGRect rectangle = CGRectMake(110,170,200,80);
            CGContextAddEllipseInRect(context, rectangle);
            CGContextStrokePath(context);
            CGContextRestoreGState(context);
    }
    
    
    -(void)gradient
    {
    //code to provide gradient effect
    
            CGContextRef context = UIGraphicsGetCurrentContext();
            CGGradientRef gradient;
            CGColorSpaceRef colorspace;
            CGFloat locations[4] = { 0.25, 0.0, 0.5, 0.75 };
        
            NSArray *colors = @[(id)[UIColor yellowColor].CGColor,
                                (id)[UIColor redColor].CGColor,
                                (id)[UIColor grayColor].CGColor,
                                (id)[UIColor greenColor].CGColor];
        
            colorspace = CGColorSpaceCreateDeviceRGB();
        
            gradient = CGGradientCreateWithColors(colorspace,
                                                  (CFArrayRef)colors, locations);
        
            CGPoint startPoint, endPoint;
            startPoint.x = 0.0;
            startPoint.y = 0.0;
        
            endPoint.x = 500;
            endPoint.y = 700;
        
            CGContextDrawLinearGradient(context, gradient,
                                        startPoint, endPoint, 0);
    }
    @end

     

     


    In subclass of UIView we created some methods to draw different shapes and with the help of drawRect method we call all those method with in switch case. Now we will move towards the coding of ViewController in which we include picker to provide option to the user.


     

    ViewController.h
    #import <UIKit/UIKit.h>
    
    @interface ViewController : UIViewController<UIPickerViewDataSource,UIPickerViewDelegate>
    {
        
        UIPickerView *picker;
        UIButton *done;
        __weak IBOutlet UIView *subView;
    }
    @property (weak, nonatomic) IBOutlet UITextField *txtUserEnteredData;
    @property (strong, nonatomic)NSArray *dataSourceArray;
    @end
    
    ViewController.m
    
    #import "ViewController.h"
    #import "SubClassOfView.h"
    
    @interface ViewController ()
    
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        picker = [[UIPickerView alloc] init];
        [done setTitle:@"Done" forState:UIControlStateNormal];
        picker.dataSource = self;
        picker.delegate = self;
        [_txtUserEnteredData setInputView:picker];
        
        _dataSourceArray = @[@"Line", @"Sphere",@"Shadow Of Circle",@"Gradient Effect"];
        UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
        toolBar.barStyle = UIBarStyleBlackOpaque;
        UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneTouched:)];
        [toolBar setItems:[NSArray arrayWithObjects:doneButton, nil]];
        _txtUserEnteredData.inputAccessoryView = toolBar;
    }
    
    
    - (void)doneTouched:(UIBarButtonItem *)sender
    {
        [_txtUserEnteredData resignFirstResponder]; // hide the picker view
        
        [(SubClassOfView*)subView setOption:_txtUserEnteredData.text]; // pass string selected by user to the subview
        [subView setNeedsDisplay];
    }
    // Do any additional setup after loading the view.
    - (NSInteger)numberOfComponentsInPickerView: (UIPickerView *)pickerView
    {
        return 1;
    }
    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
    
    {
        return  _dataSourceArray.count; //returns no of rows
    }
    - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
    {
        
        return _dataSourceArray[row];
        
    }
    -(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
    {
        NSString *resultString = _dataSourceArray[row];
        _txtUserEnteredData.text = resultString;
        if(_txtUserEnteredData.text>0)
        {
            
        }
        else
        {
            [_txtUserEnteredData setInputView:picker];
        }
        
    }
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    @end

     

     

    Output:-

    Below are the screenshots of output of the application. First screen that will be visible after execution of the application will be shown in this way :-

     

     

     

     

    After clicking on the textfield to select option a list will be appear in this way so that user can easily select one option from the given list.

     

     

     

     

    When user will select sphere from the list in this way output will be shown :-

     

     

     

     

    Output after selection of Shadow of Circle from the given list is given below:-

     

     

     

    Output after selection of Gradient Effect from the given list is given below:-

     

     

     

    You can also download the project with the help of link given below :-

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: