IOS uses cgcontextref to draw various images (text, circle, straight line, arc, rectangle, slice, elliptic, triangle, rounded rectangle, besell curve, and image)

Source: Internet
Author: User

First, let's take a look at cgcontextref:

An opaque type that represents a quartz 2D drawing environment.

Graphics context is a graphical context. It can be understood as a canvas. We can draw a canvas on it. After the painting is complete, place the canvas in our view for display, view is a frame.

I hope to help you with the demo I implemented when I learned it myself. For specific implementation, I can see the code and provide a perfect explanation. There are also some blog posts that help me for your reference. All in the code.

Take a look at the demo first:



Custom mmview class, customview. h:

#import <UIKit / UIKit.h>
#import <QuartzCore / QuartzCore.h>
#define PI 3.14159265358979323846
@interface CustomView: UIView


@end
Implementation class CustomView.m:

#import "CustomView.h"

@implementation CustomView

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


// Override the drawRect method, you can customize drawing and animation here
-(void) drawRect: (CGRect) rect
{
    // An opaque type that represents a Quartz 2D drawing environment.
    // An opaque Quartz 2D painting environment, equivalent to a canvas, you can draw on it
    CGContextRef context = UIGraphicsGetCurrentContext ();
    
    / * Write text * /
    CGContextSetRGBFillColor (context, 1, 0, 0, 1.0); // Set the fill color
    UIFont * font = [UIFont boldSystemFontOfSize: 15.0]; // Set
    [@ "画圆 :" drawInRect: CGRectMake (10, 20, 80, 20) withFont: font];
    [@ "Draw line and solitary line:" drawInRect: CGRectMake (10, 80, 100, 20) withFont: font];
    [@ "Draw rectangle:" drawInRect: CGRectMake (10, 120, 80, 20) withFont: font];
    [@ "Draw fan and ellipse:" drawInRect: CGRectMake (10, 160, 110, 20) withFont: font];
    [@ "Draw triangle:" drawInRect: CGRectMake (10, 220, 80, 20) withFont: font];
    [@ "Draw rounded rectangle:" drawInRect: CGRectMake (10, 260, 100, 20) withFont: font];
    [@ "Draw Bezier curve:" drawInRect: CGRectMake (10, 300, 100, 20) withFont: font];
    [@ "图 :" drawInRect: CGRectMake (10, 340, 80, 20) withFont: font];

    / * Draw circle * /
    // border circle
    CGContextSetRGBStrokeColor (context, 1,1,1,1.0); // The color of the brush line
    CGContextSetLineWidth (context, 1.0); // The width of the line
    // void CGContextAddArc (CGContextRef c, CGFloat x, CGFloat y, CGFloat radius, CGFloat startAngle, CGFloat endAngle, int clockwise) 1 radian = 180 ° / π (≈57.3 °) Degree = radian × 180 ° / π 360 ° = 360 × π / 180 = 2π radians
    // x, y are dot coordinates, radius of radius, startAngle is the beginning radian, endAngle is the ending radian, clockwise 0 is clockwise, 1 is counterclockwise.
    CGContextAddArc (context, 100, 20, 15, 0, 2 * PI, 0); // Add a circle
    CGContextDrawPath (context, kCGPathStroke); // Draw path
    
    // filled circle without border
    CGContextAddArc (context, 150, 30, 30, 0, 2 * PI, 0); // Add a circle
    CGContextDrawPath (context, kCGPathFill); // Draw fill
    
    // Draw a big circle and fill the face
    UIColor * aColor = [UIColor colorWithRed: 1 green: 0.0 blue: 0 alpha: 1];
    CGContextSetFillColorWithColor (context, aColor.CGColor); // Fill color
    CGContextSetLineWidth (context, 3.0); // The width of the line
    CGContextAddArc (context, 250, 40, 40, 0, 2 * PI, 0); // Add a circle
    // kCGPathFill fills non-zero winding number rules, kCGPathEOFill means to use odd-even rules, kCGPathStroke path, kCGPathFillStroke path fill, kCGPathEOFillStroke means to draw lines, not fill
    CGContextDrawPath (context, kCGPathFillStroke); // Draw path and fill
    
    / * Draw line and solitary line * /
    // Draw a line
    CGPoint aPoints [2]; // Coordinate points
    aPoints [0] = CGPointMake (100, 80); // Coordinate 1
    aPoints [1] = CGPointMake (130, 80); // Coordinate 2
    // CGContextAddLines (CGContextRef c, const CGPoint points [], size_t count)
    // points [] coordinate array, and count size
    CGContextAddLines (context, aPoints, 2); // Add lines
    CGContextDrawPath (context, kCGPathStroke); // Draw path according to coordinates
    
    // Draw a smiley arc
    //left
    CGContextSetRGBStrokeColor (context, 0, 0, 1, 1); // Change the brush color
    CGContextMoveToPoint (context, 140, 80); // Start coordinate p1
    // CGContextAddArcToPoint (CGContextRef c, CGFloat x1, CGFloat y1, CGFloat x2, CGFloat y2, CGFloat radius)
    // x1, y1 and p1 form a line coordinate p2, x2, y2 end coordinate and p3 form a line p3, radius radius
    CGContextAddArcToPoint (context, 148, 68, 156, 80, 10);
    CGContextStrokePath (context); // Drawing path
    
    //right
    CGContextMoveToPoint (context, 160, 80); // Start coordinate p1
    // CGContextAddArcToPoint (CGContextRef c, CGFloat x1, CGFloat y1, CGFloat x2, CGFloat y2, CGFloat radius)
    // x1, y1 and p1 form the coordinate p2 of a line, x2, y2 end coordinate and p3 form a line of p3, radius radius
    CGContextAddArcToPoint (context, 168, 68, 176, 80, 10);
    CGContextStrokePath (context); // Drawing path
    
    //right
    CGContextMoveToPoint (context, 150, 90); // Start coordinate p1
    // CGContextAddArcToPoint (CGContextRef c, CGFloat x1, CGFloat y1, CGFloat x2, CGFloat y2, CGFloat radius)
    // x1, y1 and p1 form the coordinate p2 of a line, x2, y2 end coordinate and p3 form a line of p3, radius radius
    CGContextAddArcToPoint (context, 158, 102, 166, 90, 10);
    CGContextStrokePath (context); // Drawing path
    // Note, if you still don't understand what is going on, please refer to: http://donbe.blog.163.com/blog/static/138048021201052093633776/
    
    / * Draw rectangle * /
    CGContextStrokeRect (context, CGRectMake (100, 120, 10, 10)); // Draw a box
    CGContextFillRect (context, CGRectMake (120, 120, 10, 10)); // Fill the box
    // Rectangle, and fill in the color
    CGContextSetLineWidth (context, 2.0); // The width of the line
    aColor = [UIColor blueColor]; // blueblue
    CGContextSetFillColorWithColor (context, aColor.CGColor); // Fill color
    aColor = [UIColor yellowColor];
    CGContextSetStrokeColorWithColor (context, aColor.CGColor); // wire frame color
    CGContextAddRect (context, CGRectMake (140, 120, 60, 30)); // Draw a box
    CGContextDrawPath (context, kCGPathFillStroke); // Drawing path
    
    // Rectangle, and fill in the gradient color
    // For color reference http://blog.sina.com.cn/s/blog_6ec3c9ce01015v3c.html
    //http://blog.csdn.net/reylen/article/details/8622932
    // The first filling method, the first method must import the class library quartcore and #import <QuartzCore / QuartzCore.h>, this is not to draw on the context, but insert the layer above the view layer. Then here is the design of Quartz Core layer programming.
    CAGradientLayer * gradient1 = [CAGradientLayer layer];
    gradient1.frame = CGRectMake (240, 120, 60, 30);
    gradient1.colors = [NSArray arrayWithObjects: (id) [UIColor whiteColor] .CGColor,
                        (id) [UIColor grayColor] .CGColor,
                        (id) [UIColor blackColor] .CGColor,
                        (id) [UIColor yellowColor] .CGColor,
                        (id) [UIColor blueColor] .CGColor,
                        (id) [UIColor redColor] .CGColor,
                        (id) [UIColor greenColor] .CGColor,
                        (id) [UIColor orangeColor] .CGColor,
                        (id) [UIColor brownColor] .CGColor, nil];
    [self.layer insertSublayer: gradient1 atIndex: 0];
    // The second filling method
    CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB ();
    CGFloat colors [] =
    {
        1,1,1, 1.00,
        1,1,0, 1.00,
        1,0,0, 1.00,
        1,0,1, 1.00,
        0,1,1, 1.00,
        0,1,0, 1.00,
        0,0,1, 1.00,
        0,0,0, 1.00,
    };
    CGGradientRef gradient = CGGradientCreateWithColorComponents
    (rgb, colors, NULL, sizeof (colors) / (sizeof (colors [0]) * 4)); // Forming the trapezoidal, gradual effect
    CGColorSpaceRelease (rgb);
    // Draw a line to form a rectangle
    // The role of CGContextSaveGState and CGContextRestoreGState
    / *
     The function of the CGContextSaveGState function is to push the current graphics state onto the stack. After that, the changes you make to the graphics state will affect the subsequent drawing operations, but will not affect the copies stored in the stack. After the modification is completed, you can use the CGContextRestoreGState function to pop the state at the top of the stack and return to the previous graphics state. This push and pop method is a quick way to return to the previous graphics state, avoiding undoing all state modifications one by one; this is also the only way to restore some states (such as the clipping path) to the original settings.
     * /
    CGContextSaveGState (context);
    CGContextMoveToPoint (context, 220, 90);
    CGContextAddLineToPoint (context, 240, 90);
    CGContextAddLineToPoint (context, 240, 110);
    CGContextAddLineToPoint (context, 220, 110);
    CGContextClip (context); // context clipping path, the path of subsequent operations
    // CGContextDrawLinearGradient (CGContextRef context, CGGradientRef gradient, CGPoint startPoint, CGPoint endPoint, CGGradientDrawingOptions options)
    // gradient gradient color, startPoint start gradient start position, endPoint end coordinate, before option start coordinate or after start start gradient
    CGContextDrawLinearGradient (context, gradient, CGPointMake
                                (220,90), CGPointMake (240,110),
                                kCGGradientDrawsAfterEndLocation);
    CGContextRestoreGState (context); // Restore to the previous context
    
    // Write another one to see the effect
    CGContextSaveGState (context);
    CGContextMoveToPoint (context, 260, 90);
    CGContextAddLineToPoint (context, 280, 90);
    CGContextAddLineToPoint (context, 280, 100);
    CGContextAddLineToPoint (context, 260, 100);
    CGContextClip (context); // Crop path
    // Frankly speaking, the start and end coordinates are the direction and shape of the control gradient
    CGContextDrawLinearGradient (context, gradient, CGPointMake
                                (260, 90), CGPointMake (260, 100),
                                kCGGradientDrawsAfterEndLocation);
    CGContextRestoreGState (context); // Restore to the previous context
    
    // Let's look at a color gradient circle below
    CGContextDrawRadialGradient (context, gradient, CGPointMake (300, 100), 0.0, CGPointMake (300, 100), 10, kCGGradientDrawsBeforeStartLocation);
    
    / * Draw fan and ellipse * /
    // Draw a fan shape, that is, draw a circle, just set the size of the angle to form a fan shape
    aColor = [UIColor colorWithRed: 0 green: 1 blue: 1 alpha: 1];
    CGContextSetFillColorWithColor (context, aColor.CGColor); // Fill color
    // Draw a sector of a specified angle around the center of the circle with a radius of 10
    CGContextMoveToPoint (context, 160, 180);
    CGContextAddArc (context, 160, 180, 30, -60 * PI / 180, -120 * PI / 180, 1);
    CGContextClosePath (context);
    CGContextDrawPath (context, kCGPathFillStroke); // Draw path

    // Draw ellipse
    CGContextAddEllipseInRect (context, CGRectMake (160, 180, 20, 8)); // Ellipse
    CGContextDrawPath (context, kCGPathFillStroke);
    
    / * Draw triangle * /
    // As long as there are three points, just like drawing a line, connect the three points
    CGPoint sPoints [3]; // Coordinate points
    sPoints [0] = CGPointMake (100, 220); // Coordinate 1
    sPoints [1] = CGPointMake (130, 220); // Coordinate 2
    sPoints [2] = CGPointMake (130, 160); // Coordinate 3
    CGContextAddLines (context, sPoints, 3); // Add lines
    CGContextClosePath (context); // Close it
    CGContextDrawPath (context, kCGPathFillStroke); // Draw path according to coordinates
    
    / * Draw rounded rectangle * /
    float fw = 180;
float fh = 280;
    
    CGContextMoveToPoint (context, fw, fh-20); // start coordinates start right
CGContextAddArcToPoint (context, fw, fh, fw-20, fh, 10); // Angle of the lower right corner
CGContextAddArcToPoint (context, 120, fh, 120, fh-20, 10); // Angle of the lower left corner
CGContextAddArcToPoint (context, 120, 250, fw-20, 250, 10); // upper left corner
CGContextAddArcToPoint (context, fw, 250, fw, fh-20, 10); // upper right corner
CGContextClosePath (context);
    CGContextDrawPath (context, kCGPathFillStroke); // Draw path according to coordinates
    
    / * Draw Bezier curve * /
    // Conic
    CGContextMoveToPoint (context, 120, 300); // Set the starting point of Path
    CGContextAddQuadCurveToPoint (context, 190, 310, 120, 390); // Set the control point coordinates and end point coordinates of the Bezier curve
    CGContextStrokePath (context);
    // Cubic curve function
    CGContextMoveToPoint (context, 200, 300); // Set the starting point of Path
    CGContextAddCurveToPoint (context, 250, 280, 250, 400, 280, 300); // Set the control point coordinates and end point coordinates of the Bezier curve
    CGContextStrokePath (context);
    
    
    /*image*/
    UIImage * image = [UIImage imageNamed: @ "apple.jpg"];
    [image drawInRect: CGRectMake (60, 340, 20, 20)]; // Draw a picture in coordinates
// [image drawAtPoint: CGPointMake (100, 340)]; // Keep the picture size at the point and start drawing the picture, you can remove the comment to see
    CGContextDrawImage (context, CGRectMake (100, 340, 20, 20), image.CGImage); // Use this to make the picture upside down, refer to http://blog.csdn.net/koupoo/article/details/8670024
    
// CGContextDrawTiledImage (context, CGRectMake (0, 0, 20, 20), image.CGImage); // Tiled image

}


@end
usage:

CustomView * customView = [[CustomView alloc] initWithFrame: CGRectMake (0, 0, 320, self.view.frame.size.height)];
    [self.view addSubview: customView];
ok, complete.

If you have seen my other blogs, you will find that this blog is very similar to one of my blogs, yes, it is http://blog.csdn.net/rhljiayou/article/details/7212620

I wrote a blog once when I wrote andriod.

Please respect my successful labor, please indicate the original address when reprinting!

http://blog.csdn.net/rhljiayou/article/details/9919713

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.