IPhone quartz 2d series-graphic context (2) graphics contexts

Source: Internet
Author: User

The following several times on the quartz 2D blog are reproduced from: http://www.cocoachina.com/bbs/u.php? Action = topics & uid = 38018

For the code implementation of this chapter's blog, you can refer to this blog: IOS uses cgcontextref to draw various images (text, circle, straight line, arc, rectangle, slice, elliptic, triangle, rounded rectangle, besell curve, and image)

Apple official website English Introduction: https://developer.apple.com/library/mac/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_overview/dq_overview.html#//apple_ref/doc/uid/TP30001066-CH202-TPXREF101

IPhone quartz 2d series-graphic context (2) (Graphics contexts)

A graphics context indicates a drawing target. It contains the drawing parameters and device information used by the drawing system to complete the drawing command. Graphics context defines basic drawing attributes, such as color, cut area, line width and style information, font information, and mixed mode.

You can obtain the functions provided by graphics context: quartz, the Mac OS X framework, or the IOS uikit framework in several ways. Quartz provides a variety of graphics context creation functions, including bitmap and PDF. We can use these graphics context to create custom content.

This chapter describes how to create graphics context for different drawing targets. In the code, cgcontextref is used to represent a graphics context. After obtaining a graphics context, you can use the quartz 2D function to draw and complete operations (such as translation) in the context, and modify graphics status parameters (such as linewidth and fill color.

Draw graphics context in IOS
In IOS apps, if you want to draw on the screen, you need to create a uiview object and implement its drawrect: method. View drawrect: The method is called when the view is displayed on the screen and its content needs to be updated. After the custom drawrect: is called, the view object automatically configures the drawing environment so that the code can immediately perform the Drawing operation. As part of the configuration, the view object creates a graphics context for the current drawing environment. We can call the uigraphicsgetcurrentcontext function to obtain the graphics context.

The default Coordinate System of uikit is different from that of quartz. In uikit, the origin is in the upper left corner, and the positive direction of the Y axis is downward. Uiview matches uiview by translating the CTM of graphics context of quartz to the lower left corner and reversing the Y axis (Y value multiplied by-1.

Create a window graphics context in Mac OS X
When drawing in Mac OS X, we need to create a window graphics context. The quartz 2D API does not provide functions to obtain the window graphics context. Instead, we use the cocoa framework to obtain a window context.

We can get a quartz graphics context in drawrect: of the cocoa application, as shown in the following code:

Copy code

  1. Cgcontextref mycontext = [[nsgraphicscontext currentcontext] graphicsport];

The currentcontext method returns the nsgraphicscontext instance in the current thread. The graphicsport method returns a low-level and platform-related graphics context (quartz graphics context ).

After obtaining graphics context, we can call any quartz 2D rendering function in the cocoa application. We can also mix quartz 2D and cocoa painting operations. 2-1 is an instance drawn with quartz 2D in the cocoa view. The drawing consists of two rectangles (an opaque red rectangle and a translucent blue rectangle ).


To implement the instance shown in Figure 2-1, you must first create a cocoa application. In interface builder, drag a m View to the window and subclass it. Then implement the subclass view, as shown in code list 2-1. View drawrect: contains all the quartz drawing code.

REFERENCE Note: drawrect of nsview: This method is automatically called every time the view needs to be drawn.

Copy code

  1. Listing 2-1 drawing to a window graphics context
  2. @ Implementation myquartzview
  3. -(ID) initwithframe :( nsrect) framerect
  4. {
  5. Self = [Super initwithframe: framerect];
  6. Return self;
  7. }
  8. -(Void) drawrect :( nsrect) Rec
  9. {
  10. Cgcontextref mycontext = [[nsgraphicscontext currentcontext] graphicsport]; // 1
  11. // ********** Your drawing code here ************ // 2
  12. Cgcontextsetrgbfillcolor (mycontext, 1, 0, 0, 1); // 3
  13. Cgcontextfillrect (mycontext, cgrectmake (0, 0,200,100); // 4
  14. Cgcontextsetrgbfillcolor (mycontext, 0, 0, 1,. 5); // 5
  15. Cgcontextfillrect (mycontext, cgrectmake (0, 0,100,200); // 6
  16. }
  17. @ End


Code Description:
1. Obtain a graphics context for the view
2. Insert the drawing code. The following are examples of using the quartz 2D function:
3. Set a completely opaque red fill color.
4. Fill in a rectangle. Its origin is (0, 0) and its size is (200,100)
5. Set a translucent blue fill color.
6. Fill in a rectangle. Its origin is (0, 0) and its size is (100,200)

Create a PDF graphics context
When a PDF graphics context is created and drawn, quartz records the Drawing operation as a series of PDF drawing commands and writes them to the file. We need to provide a PDF output location and a default media box (used to specify the rectangle of the page boundary ). Figure 2-2 shows the result of drawing in the PDF graphics context and opening the PDF in the preview.


The quartz 2D API provides two functions to create a PDF graphics context:

  • Cgw.contextcreatewithurl: this function is used when you need to use the core foundation URL to specify the position of the PDF output. The code list 2-2 shows how to use the function (Code 2-2 and the detailed explanation of the code below ):

Copy code

  1. Listing 2-2 calling cg1_contextcreatewithurl to create a PDF graphics context
  2. Cgcontextref my‑contextcreate (const cgrect * inmediabox, cfstringref path)
  3. {
  4. Cgcontextref myoutcontext = NULL;
  5. Cfurlref URL;
  6. Url = cfurlcreatewithfilesystempath (null, path, kcfurlposixpathstyle, false );
  7. If (URL! = NULL ){
  8. Myoutcontext = cgmediacontextcreatewithurl (URL, inmediabox, null );
  9. Cfrelease (URL );
  10. }
  11. Return myoutcontext;
  12. }

  • Cgw.contextcreate: This method is used to send PDF output to data users. The code list 2-3 shows how to use the function:

Copy code

  1. Listing 2-3 calling cg1_contextcreate to create a PDF graphics context
  2. Cgcontextref my‑contextcreate (const cgrect * inmediabox, cfstringref path)
  3. {
  4. Cgcontextref myoutcontext = NULL;
  5. Cfurlref URL;
  6. Cgdataconsumerref dataconsumer;
  7. Url = cfurlcreatewithfilesystempath (null, path, kcfurlposixpathstyle, false );
  8. If (URL! = NULL)
  9. {
  10. Dataconsumer = cgdataconsumercreatewithurl (URL );
  11. If (dataconsumer! = NULL)
  12. {
  13. Myoutcontext = cg1_contextcreate (dataconsumer, inmediabox, null );
  14. Cgdataconsumerrelease (dataconsumer );
  15. }
  16. Cfrelease (URL );
  17. }
  18. Return myoutcontext;
  19. }


The code list 2-4 shows how to call and draw the my‑contextcreate program.

Copy code

  1. Listing 2-4 drawing to a PDF graphics context
  2. Cgrect mediabox;
  3. Mediabox = cgrectmake (0, 0, mypagewidth, mypageheight );
  4. Mydomaincontext = mydomaincontextcreate (& mediabox, cfstr ("testbench "));
  5. Cfstringref mykeys [1];
  6. Cftyperef myvalues [1];
  7. Mykeys [0] = kcg1_contextmediabox;
  8. Myvalues [0] = (cftyperef) cfdatacreate (null, (const uint8 *) & mediabox, sizeof (cgrect ));
  9. Cfdictionaryref pagedictionary = cfdictionarycreate (null, (const void **) mykeys,
  10. (Const void **) myvalues, 1,
  11. & Kcftypedictionarykeycallbacks,
  12. & Kcftypedictionaryvaluecallbacks );
  13. Cgw.contextbeginpage (mydomaincontext, & pagedictionary );
  14. // ********** Your drawing code here **********
  15. Cgcontextsetrgbfillcolor (mydomaincontext, 1, 0, 0, 1 );
  16. Cgcontextfillrect (mydomaincontext, cgrectmake (0, 0,200,100 ));
  17. Cgcontextsetrgbfillcolor (mydomaincontext, 0, 0, 1,. 5 );
  18. Cgcontextfillrect (mydomaincontext, cgrectmake (0, 0,100,200 ));
  19. Cgw.contextendpage (mydomaincontext );
  20. Cfrelease (pagedictionary );
  21. Cfrelease (myvalues [0]);
  22. Cgcontextrelease (mydomaincontext );


We can draw any content (images, text, and paths) to PDF, and add links and encryption.

Create a bitmap graphics context
A bitmap graphics context receives a pointer to the memory cache (including the bitmap bucket). When we draw a bitmap graphics context, the cache is updated. After graphics context is released, a new bitmap in the specified pixel format is obtained.

REFERENCE Note: bitmap graphics context is sometimes used for background painting. The cglayer object optimizes background rendering because quartz caches layers on the video card.

Reference IOS tips: IOS apps use uigraphicsbeginimagecontextwitexceptions to replace the quartz lower-level functions. If you use quartz to create a background bitmap, the coordinate system used by bitmap graphics context is the default Coordinate System of quartz. When uigraphicsbeginimagecontextwitexceptions is used to create a graphic context, uikit will convert the coordinate system using the same image context as the uiview object. This allows applications to use the same drawing code without worrying about coordinate system issues. Although our application can manually adjust the CTM to achieve the same effect, this does not have any advantages.

We use cgbitmapcontextcreate to create the bitmap graphics context. This function has the following parameters:

  • Data: a pointer to the memory target, which is used to store the graphic data to be rendered. The size of the memory block must be at least byteperrow * height.
  • Width: Specify the width of the bitmap, in pixels ).
  • Height: Specify the height of the bitmap, in pixels ).
  • Bitspercomponent: specifies the number of digits used by each component in one pixel of memory. For example, for a 32-bit pixel format and an RGB color space, we can specify each component as eight bits.
  • Bytesperrow: specifies the number of bytes in each row of the bitmap.
  • Colorspace: color space is used for bitmap context. When creating a bitmap graphics context, we can use Gray, RGB, CMYK, and null color spaces.
  • Bitmapinfo: bitmap information, which is used to specify whether the bitmap needs to contain the Alpha component, the relative position (if any) of the Alpha component in the pixel, and whether the Alpha component is premultiplied, and whether the color component is an integer or floating point value.

The code list 2-5 shows how to create a bitmap graphics context. When drawing to the bitmap graphics context, quartz records the drawing to the block specified in the memory.

Copy code

  1. Listing 2-5 creating a bitmap graphics context
  2. Cgcontextref mycreatebitmapcontext (INT pixelswide, int pixelshigh)
  3. {
  4. Cgcontextref context = NULL;
  5. Cgcolorspaceref colorspace;
  6. Void * bitmapdata;
  7. Int bitmapbytecount;
  8. Int bitmapbytesperrow;
  9. Bitmapbytesperrow = (pixelswide * 4 );
  10. Bitmapbytecount = (bitmapbytesperrow * pixelshigh );
  11. Colorspace = cgcolorspacecreatewithname (kcgcolorspacegenericrgb );
  12. Bitmapdata = calloc (bitmapbytecount );
  13. If (bitmapdata = NULL)
  14. {
  15. Fprintf (stderr, "memory not allocated! ");
  16. Return NULL;
  17. }
  18. Context = cgbitmapcontextcreate (bitmapdata, pixelswide, pixelshigh, 8, bitmapbytesperrow, colorspace, kcgimagealphapremultipliedlast );
  19. If (context = NULL)
  20. {
  21. Free (bitmapdata );
  22. Fprintf (stderr, "context not created! ");
  23. Return NULL;
  24. }
  25. Cgcolorspacerelstrap (colorspace );
  26. Return context;
  27. }

In the code list, 2-6 shows how to call mycreatebitmapcontext to create a bitmap graphics context, use the bitmap graphics context to create a cgimage object, and then draw the image to the window graphics context. The rendering result is as follows:

Copy code

  1. Listing 2-6 drawing to a bitmap graphics context
  2. Cgrect myboundingbox;
  3. Myboundingbox = cgrectmake (0, 0, mywidth, myheight );
  4. Mybitmapcontext = mycreatebitmapcontext (400,300 );
  5. // ********** Your drawing code here **********
  6. Cgcontextsetrgbfillcolor (mybitmapcontext, 1, 0, 0, 1 );
  7. Cgcontextfillrect (mybitmapcontext, cgrectmake (0, 0,200,100 ));
  8. Cgcontextsetrgbfillcolor (mybitmapcontext, 0, 0, 1,. 5 );
  9. Cgcontextfillrect (mybitmapcontext, cgrectmake (0, 0,100,200 ));
  10. Myimage = cgbitmapcontextcreateimage (mybitmapcontext );
  11. Cgcontextdrawimage (mycontext, myboundingbox, myimage );
  12. Char * bitmapdata = cgbitmapcontextgetdata (mybitmapcontext );
  13. Cgcontextrelease (mybitmapcontext );
  14. If (bitmapdata) Free (bitmapdata );
  15. Cgimagerelease (myimage );


Supported pixel formats
Table 2-1 summarizes the pixel formats supported by the bitmap graphics context, the color space, and the oldest Mac OS X versions supported by the pixel format. The pixel format is represented by BPP (the number of digits per pixel) and BPC (the number of digits per component. The table also contains bitmap information constants related to the pixel format.

Table 2-1: pixel formats supported by the bitmap graphics context

Null 8 bpp, 8 BPC,
Kcgimagealphaonly
Mac OS X, IOS
Gray 8 bpp, 8 BPC, kcgimagealphanone Mac OS X, IOS
Gray 8 bpp, 8 BPC, kcgimagealphaonly Mac OS X, IOS
Gray 16 bpp, 16 BPC,
Kcgimagealphanone
Mac OS X
Gray 32 bpp, 32 BPC,
Kcgimagealphanone | kcgbitmapfloatcomponents
Mac OS X
RGB 16 bpp, 5 BPC,
Kcgimagealphanoneskipfirst
Mac OS X, IOS
RGB 32 bpp, 8 BPC,
Kcgimagealphanoneskipfirst
Mac OS X, IOS
RGB 32 bpp, 8 BPC,
Kcgimagealphanoneskiplast
Mac OS X, IOS
RGB 32 bpp, 8 BPC,
Kcgimagealphapremultipliedfirst
Mac OS X, IOS
RGB 32 bpp, 8 BPC,
Kcgimagealphapremultipliedlast
Mac OS X, IOS
RGB 64 bpp, 16 BPC,
Kcgimagealphapremultipliedlast
Mac OS X
RGB 64 bpp, 16 BPC,
Kcgimagealphanoneskiplast
Mac OS X
RGB 128 bpp, 32 BPC,
Kcgimagealphanoneskiplast | kcgbitmapfloatcomponents
Mac OS X
RGB 128 bpp, 32 BPC,
Kcgimagealphapremultipliedlast | kcgbitmapfloatcomponents
Mac OS X
CMYK 32 bpp, 8 BPC,
Kcgimagealphanone
Mac OS X
CMYK 64 bpp, 16 BPC,
Kcgimagealphanone
Mac OS X
CMYK 128 bpp, 32 BPC,
Kcgimagealphanone | kcgbitmapfloatcomponents
Mac OS X

Anti-sawtooth
The bitmap graphics context supports anti-sawtooth. This operation is a jagged edge generated when a text or shape is drawn in a positive image. When the bitmap resolution is significantly lower than the resolution of the human eye, it will produce sawtooth. In order to make the objects in the bitmap look smooth, quartz uses different colors to fill the pixels around the shape. In this way, colors are mixed to make the shape look smoother. 2-4. You can call cgcontextsetshouldantialias to disable the anti-sawtooth effect of the bitmap graphics context. The anti-sawtooth setting is part of the graph status.
You can call the cgcontextsetallowsantialiasing function to control whether a specific graphics context supports anti-aliasing. False indicates not. This setting is not part of the graph status. When the context and image status are set to true, quartz executes anti-aliasing.

Obtain the printed graphics context

The cocoa application in Mac OS X is printed using the custom nsview subclass. A view is printed by calling the print method. The view then creates a graphics context with the printer as the target and calls the drawrect: method. The application uses the same drawing code as drawing on the screen. We can also customize the drawrect: Method to draw graphics to the printer.

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.