Quartz2D

Creating a Bitmap Graphics Context

You use the function  CGBitmapContextCreate  to create a bitmap graphics context. This function takes the following parameters:

CGContextRef CGBitmapContextCreate (
   void *data,
   size_t width,
   size_t height,
   size_t bitsPerComponent,
   size_t bytesPerRow,
   CGColorSpaceRef colorspace,
   CGBitmapInfo bitmapInfo
);

Creating a Path
  • CGPathCreateMutable, which replacesCGContextBeginPath

  • CGPathMoveToPoint, which replaces CGContextMoveToPoint

  • CGPathAddLineToPoint, which replaces CGContextAddLineToPoint

  • CGPathAddCurveToPoint, which replaces CGContextAddCurveToPoint

  • CGPathAddEllipseInRect, which replaces CGContextAddEllipseInRect

  • CGPathAddArc, which replaces CGContextAddArc

  • CGPathAddRect, which replaces CGContextAddRect

  • CGPathCloseSubpath, which replaces CGContextClosePath

填充一个路径的时候,路径里面的子路径都是独立填充的。
假如是重叠的路径,决定一个点是否被填充,有两种规则
1,nonzero winding number rule:非零绕数规则,假如一个点被从左到右跨过,计数器+1,从右到左跨过,计数器-1,最后,如果结果是0,那么不填充,如果是非零,那么填充。
2,even-odd rule: 奇偶规则,假如一个点被跨过,那么+1,最后是奇数,那么要被填充,偶数则不填充,和方向没有关系。


Function
Description 
CGContextEOFillPath
使用奇偶规则填充当前路径
CGContextFillPath
使用非零绕数规则填充当前路径
CGContextFillRect
填充指定的矩形
CGContextFillRects
填充指定的一些矩形
CGContextFillEllipseInRect
填充指定矩形中的椭圆
CGContextDrawPath
两个参数决定填充规则,kCGPathFill表示用非零绕数规则,kCGPathEOFill表示用奇偶规则,kCGPathFillStroke表示填充,kCGPathEOFillStroke表示描线,不是填充

Clipping to a Path -留下的是要显示的

The current clipping area is created from a path that serves as a mask, allowing you to block out the part of the page that you don’t want to paint. For example, if you have a very large bitmap image and want to show only a small portion of it, you could set the clipping area to display only the portion you want to show.

 
    
static inline double radians (double degrees) {return degrees * M_PI/180;}

Getting the User to Device Space Transform

Typically when you draw with Quartz 2D, you work only in user space. Quartz takes care of transforming between user and device space for you. If your application needs to obtain the affine transform that Quartz uses to convert between user and device space, you can call the function CGContextGetUserSpaceToDeviceSpaceTransform.

Quartz provides a number of convenience functions to transform the following geometries between user space and device space. You might find these functions easier to use than applying the affine transform returned from the functionCGContextGetUserSpaceToDeviceSpaceTransform.

  • Points. The functions CGContextConvertPointToDeviceSpace and CGContextConvertPointToUserSpace transform a CGPoint data type from one space to the other.

  • Sizes. The functions CGContextConvertSizeToDeviceSpace and CGContextConvertSizeToUserSpace transform aCGSize data type from one space to the other.

  • Rectangles. The functions CGContextConvertRectToDeviceSpace and CGContextConvertRectToUserSpacetransform a CGRect data type from one space to the other.

How Patterns Work

Patterns operate similarly to colors, in that you set a fill or stroke pattern and then call a painting function. Quartz uses the pattern you set as the “paint.” For example, if you want to paint a filled rectangle with a solid color, you first call a function, such as CGContextSetFillColor, to set the fill color. Then you call the function CGContextFillRect to paint the filled rectangle with the color you specify. To paint with a pattern, you first call the function CGContextSetFillPattern to set the pattern. Then you call CGContextFillRectto actually paint the filled rectangle with the pattern you specify. The difference between painting with colors and with patterns is that you must define the pattern. You supply the pattern and color information to the function CGContextSetFillPattern

Painting Colored Patterns

The five steps you need to perform to paint a colored pattern are described in the following sections:

  1. “Write a Callback Function That Draws a Colored Pattern Cell”

  2. “Set Up the Colored Pattern Color Space”

  3. “Set Up the Anatomy of the Colored Pattern”

  4. “Specify the Colored Pattern as a Fill or Stroke Pattern”

  5. “Draw With the Colored Pattern”

void ColoredPatternCallback (void *info ,CGContextRef context)

{

    CGFloat subunit =5;

    CGRect myRect1 = {{0,0},{subunit,subunit}};

    CGRect myRect2 = {{subunit ,subunit},{subunit,subunit}};

    CGRect myRect3 = {{0 ,subunit},{subunit,subunit}};

    CGRect myRect4 = {{subunit ,0},{subunit,subunit}};

    

    CGContextSetRGBFillColor(context,0,0,1,0.5);

    CGContextFillRect(context, myRect1);

    CGContextSetRGBFillColor(context,1,0,0,0.5);

    CGContextFillRect(context, myRect2);

    CGContextSetRGBFillColor(context,0,1,0,0.5);

    CGContextFillRect(context, myRect3);

    CGContextSetRGBFillColor(context,0.5,0,0.5,.5);

    CGContextFillRect(context, myRect4);

}

- (void)drawRect:(CGRect)rect

{

    CGColorSpaceRef patterSpace;

    CGPatternRef pattern;

    CGFloat alpha =1;

    

    CGContextRef context =UIGraphicsGetCurrentContext();

    static const CGPatternCallbacks callBacks = {0 ,&ColoredPatternCallback,NULL};

    CGContextSaveGState(context);

    patterSpace = CGColorSpaceCreatePattern(NULL);

    CGContextSetFillColorSpace(context, patterSpace);

    CGColorSpaceRelease(patterSpace);

    

    pattern = CGPatternCreate(NULL,

                              CGRectMake(0,0,10,10),

                              CGAffineTransformIdentity,

                              20, 20,

                              kCGPatternTilingConstantSpacing,

                              YES,

                              &callBacks);

    

    CGContextSetFillPattern(context, pattern, &alpha);

    CGPatternRelease(pattern);

    CGContextFillRect(context,CGRectMake(20,20,200,200));

    CGContextRestoreGState(context);

}

//另一种方式,从pattern 抽取出颜色

CGPatternCallbacks coloredPatternCallbacks = {0,ColoredPatternCallback,NULL};

// First we need to create a CGPatternRef that specifies the qualities of our pattern.


CGPatternRef coloredPattern =CGPatternCreate(

NULL,// 'info' pointer for our callback

CGRectMake(0.0,0.0,16.0,16.0),// the pattern coordinate space, drawing is clipped to this rectangle

CGAffineTransformIdentity,// a transform on the pattern coordinate space used before it is drawn.

16.0,16.0,// the spacing (horizontal, vertical) of the pattern - how far to move after drawing each cell

kCGPatternTilingNoDistortion,

true,// this is a colored pattern, which means that you only specify an alpha value when drawing it

&coloredPatternCallbacks);// the callbacks for this pattern.


// To draw a pattern, you need a pattern colorspace.

// Since this is an colored pattern, the parent colorspace is NULL, indicating that it only has an alpha value.

CGColorSpaceRef coloredPatternColorSpace =CGColorSpaceCreatePattern(NULL);

CGFloat alpha =1.0;

// Since this pattern is colored, we'll create a CGColorRef for it to make drawing it easier and more efficient.

// From here on, the colored pattern is referenced entirely via the associated CGColorRef rather than the

// originally created CGPatternRef.


coloredPatternColor =CGColorCreateWithPattern(coloredPatternColorSpace, coloredPattern, &alpha);

CGColorSpaceRelease(coloredPatternColorSpace);

CGPatternRelease(coloredPattern);


//直接用颜色来绘制

// Draw the colored pattern. Since we have a CGColorRef for this pattern, we just set

// that color current and draw.

CGContextSetFillColorWithColor(context,coloredPatternColor);

CGContextFillRect(context,CGRectMake(10.0,10.0,90.0,90.0));


Painting Stencil Patterns

The five steps you need to perform to paint a stencil pattern are described in the following sections:

  1. “Write a Callback Function That Draws a Stencil Pattern Cell”

  2. “Set Up the Stencil Pattern Color Space”

  3. “Set Up the Anatomy of the Stencil Pattern”

  4. “Specify the Stencil Pattern as a Fill or Stroke Pattern”

  5. “Drawing with the Stencil Pattern”

void UnColoredPatternCallBack(void *info,CGContextRef context)

{

    int k;

    double r,theta;

    

    r = 0.8*PSIZE/2;

    theta = 2 *M_PI *(2.0/5.0);

    

    CGContextTranslateCTM(context,PSIZE/2,PSIZE/2);

    CGContextMoveToPoint(context,0, r);

    for (k = 1; k <5; k++)

    {

        CGContextAddLineToPoint(context, r*sin(k*theta), r *cos(k*theta));

    }

    CGContextClosePath(context);

    CGContextFillPath(context);

}


- (void)drawRect:(CGRect)rect

{

    CGPatternRef uncolorPattern;

    CGColorSpaceRef baseSpace;

    CGColorSpaceRef patternSpace;

    

   //设定颜色值

    static const CGFloat color[] ={1,1,0,1};

    static const CGPatternCallbacks callBack = {0,&UnColoredPatternCallBack,NULL};

    

    baseSpace = CGColorSpaceCreateDeviceRGB();

    patternSpace = CGColorSpaceCreatePattern(baseSpace);

    

    CGContextSetFillColorSpace(context, patternSpace);

    CGColorSpaceRelease(patternSpace);

    CGColorSpaceRelease(baseSpace);

    

    uncolorPattern = CGPatternCreate(NULL,

                                     CGRectMake(0,0,PSIZE,PSIZE),

                                     CGAffineTransformIdentity,

                                     PSIZE,PSIZE,

                                     kCGPatternTilingConstantSpacing,

                                     NO, &callBack);

    CGContextSetFillPattern(context, uncolorPattern, color);

    CGPatternRelease(uncolorPattern);

    CGContextFillRect(context,CGRectMake(20,300,200,100));

}

How Shadows Work

Shadows in Quartz are part of the graphics state. You call the function CGContextSetShadow, passing a graphics context, offset values, and a blur value. After shadowing is set, any object you draw has a shadow drawn with a black color that has a 1/3 alpha value in the device RGB color space. In other words, the shadow is drawn using RGBA values set to {0, 0, 0, 1.0/3.0}.

You can draw colored shadows by calling the function CGContextSetShadowWithColor, passing a graphics context, offset values, a blur value, and a CGColor object. The values to supply for the color depend on the color space you want to draw in.

If you save the graphics state before you call CGContextSetShadow or CGContextSetShadowWithColor, you can turn off shadowing by restoring the graphics state. You also disable shadows by setting the shadow color to NULL.

//默认黑色阴影风格

    CGContextSetShadow(context,CGSizeMake(10,10),5);

//自定义颜色阴影

    CGContextSetShadowWithColor(context,CGSizeMake(0,20),4, [UIColorredColor].CGColor);


Gradients

  Differences between CGShading and CGGradient objects

CGGradient

CGShading

Can use the same object to draw axial and radial gradients.

Need to create separate objects for axial and radial gradients.

Set the geometry of the gradient at drawing time.

Set the geometry of the gradient at object creation time.

Quartz calculates the colors for each point in the gradient.

You must supply a callback function that calculates the colors for each point in the gradient.

Easy to define more than two locations and colors.

Need to design your callback to use more than two locations and colors, so it takes a bit more work on your part.

Using a CGGradient Object

  1. Create a CGGradient object, supplying a color space, an array of two or more color components, an array of two or more locations, and the number of items in each of the two arrays.

  2. Paint the gradient by calling either CGContextDrawLinearGradient orCGContextDrawRadialGradient and supplying a context, a CGGradient object, drawing options, and the stating and ending geometry (points for axial gradients or circle centers and radii for radial gradients).

  3. Release the CGGradient object when you no longer need it.

    CGGradientRef myGradient;

    CGColorSpaceRef colorSpace;

    size_t num = 2.0;

    

    CGFloat location[2] = {0.0 ,1.0};

    CGFloat components[8] = {1.0,.5,.4,1.0,

        .8,.8,.3,1.0};

    

    colorSpace = CGColorSpaceCreateDeviceRGB();

    myGradient = CGGradientCreateWithColorComponents(colorSpace, components, location, num);


    CGPoint startpoint =CGPointMake(320.0,0.0);

    CGPoint endpoint =CGPointMake(0.0,320.0);

//    计算这两点的距离方向,用两点间的距离然后平行铺满整个contenxt

    CGContextDrawLinearGradient(context, myGradient, startpoint, endpoint,0);



CGPoint myStartPoint, myEndPoint;
CGFloat myStartRadius, myEndRadius;
myStartPoint.x = 0.15;
myStartPoint.y = 0.15;
myEndPoint.x = 10.5;
myEndPoint.y = 10;
myStartRadius = 10.1;
myEndRadius = 10.25;
CGContextDrawRadialGradient (myContext, myGradient, myStartPoint,
                         myStartRadius, myEndPoint, myEndRadius,
                         kCGGradientDrawsAfterEndLocation);

Using a CGShading Object

You set up a gradient by creating a CGShading object calling the function  CGShadingCreateAxial  or CGShadingCreateRadial

To paint the axial gradient shown in the figure, follow the steps explained in these sections:

  1. “Set Up a CGFunction Object to Compute Color Values”

  2. “Create a CGShading Object for an Axial Gradient”

  3. “Clip the Context”

  4. “Paint the Axial Gradient Using a CGShading Object”

  5. “Release Objects”

1.
static void myCalculateShadingValues (void *info,
                            const CGFloat *in,
                            CGFloat *out)
{
    CGFloat v;
    size_t k, components;
    static const CGFloat c[] = {1, 0, .5, 0 };
 
    components = (size_t)info;
 
    v = *in;
    for (k = 0; k < components -1; k++)
        *out++ = c[k] * v;
     *out++ = 1;
}

 
static CGFunctionRef myGetFunction (CGColorSpaceRef colorspace)// 1
{
    size_t numComponents;
    static const CGFloat input_value_range [2] = { 0, 1 };
    static const CGFloat output_value_ranges [8] = { 0, 1, 0, 1, 0, 1, 0, 1 };
    static const CGFunctionCallbacks callbacks = { 0,// 2
                                &myCalculateShadingValues,
                                NULL };
 
    numComponents = 1 + CGColorSpaceGetNumberOfComponents (colorspace);// 3
    return CGFunctionCreate ((void *) numComponents, // 4
                                1, // 5
                                input_value_range, // 6
                                numComponents, // 7
                                output_value_ranges, // 8
                                &callbacks);// 9
}

2.
CGPoint     startPoint,
            endPoint;
CGFunctionRef myFunctionObject;
CGShadingRef myShading;
 
startPoint = CGPointMake(0,0.5);
endPoint = CGPointMake(1,0.5);
colorspace = CGColorSpaceCreateDeviceRGB();
myFunctionObject = myGetFunction (colorspace);
 
myShading = CGShadingCreateAxial (colorspace,
                        startPoint, endPoint,
                        myFunctionObject,
                        false, false);
3.
    CGContextBeginPath (myContext);
    CGContextAddArc (myContext, .5, .5, .3, 0,
                    my_convert_to_radians (180), 0);
    CGContextClosePath (myContext);
    CGContextClip (myContext);
4.
CGContextDrawShading (myContext, myShading);
5.
CGShadingRelease (myShading);
CGColorSpaceRelease (colorspace);
CGFunctionRelease (myFunctionObject);

How Transparency Layers Work

You signal the start of a transparency layer by calling the function  CGContextBeginTransparencyLayer , which takes as parameters a graphics context and a CFDictionary object. The dictionary lets you provide options to specify additional information about the layer, but because the dictionary is not yet used by the Quartz 2D API, you pass  NULL .After this call, graphics state parameters remain unchanged except for alpha (which is set to  1), shadow (which is turned off), blend mode (which is set to normal), and other parameters that affect the final composite.

After you begin a transparency layer, you perform whatever drawing you want to appear in that layer.

When you are finished drawing, you call the function CGContextEndTransparencyLayer. Quartz composites the result into the context using the global alpha value and shadow state of the context and respecting the clipping area of the context.

Painting to a transparency layer requires three steps:

  1. Call the function CGContextBeginTransparencyLayer.

  2. Draw the items you want to composite in the transparency layer.

  3. Call the function CGContextEndTransparencyLayer.

Opening and Viewing a PDF

You create a CGPDFDocument object using either the function  CGPDFDocumentCreateWithProvider  or the function   CGPDFDocumentCreateWithURL

 Creating a CGPDFDocument object from a PDF file

CGPDFDocumentRef MyGetPDFDocumentRef (const char *filename)
{
    CFStringRef path;
    CFURLRef url;
    CGPDFDocumentRef document;
    size_t count;
 
    path = CFStringCreateWithCString (NULL, filename,
                         kCFStringEncodingUTF8);
    url = CFURLCreateWithFileSystemPath (NULL, path, // 1
                        kCFURLPOSIXPathStyle, 0);
    CFRelease (path);
    document = CGPDFDocumentCreateWithURL (url);// 2
    CFRelease(url);
    count = CGPDFDocumentGetNumberOfPages (document);// 3
    if (count == 0) {
        printf("`%s' needs at least one page!", filename);
        return NULL;
    }
    return document;
}

Drawing a PDF page

void MyDisplayPDFPage (CGContextRef myContext,
                    size_t pageNumber,
                    const char *filename)
{
    CGPDFDocumentRef document;
    CGPDFPageRef page;
 
    document = MyGetPDFDocumentRef (filename);// 1
    page = CGPDFDocumentGetPage (document, pageNumber);// 2
    CGContextDrawPDFPage (myContext, page);// 3
    CGPDFDocumentRelease (document);// 4
}

Creating a Transform for a PDF Page

Quartz provides a function—CGPDFPageGetDrawingTransform—that creates an affine transform by mapping a box in a PDF page to a rectangle you specify. The prototype for this function is:

CGAffineTransform CGPDFPageGetDrawingTransform (
        CGPPageRef page,
        CGPDFBox box,
        CGRect rect,
        int rotate,
        bool preserveAspectRatio
);
   CGAffineTransform m;
 
    m = CGPDFPageGetDrawingTransform (page, box, rect, rotation,// 1
                                    preserveAspectRato);
    CGContextSaveGState (context);// 2
    CGContextConcatCTM (context, m);// 3
    CGContextClipToRect (context,CGPDFPageGetBoxRect (page, box));// 4
    CGContextDrawPDFPage (context, page);// 5
    CGContextRestoreGState (context);

Creating a PDF File

   NSString *docum = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0];

    NSString *path = [documstringByAppendingPathComponent:@"haohai.pdf"];

    createPdfFile(self.view.bounds, [pathcStringUsingEncoding:NSUTF8StringEncoding]);


void createPdfFile(CGRect pageRect ,constchar* filename)

{

    CGContextRef pdfContext;

    CFStringRef path;

    CFURLRef url;

    

    CFDataRef boxData = NULL;

    CFMutableDictionaryRef myDic =NULL;

    CFMutableDictionaryRef pageDic =NULL;

    

    path = CFStringCreateWithCString(NULL, filename,kCFStringEncodingUTF8);

    url = CFURLCreateWithFileSystemPath(NULL, path,kCFURLPOSIXPathStyle,0);

    CFRelease(path);

    

    myDic = CFDictionaryCreateMutable(NULL,0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    CFDictionarySetValue(myDic,kCGPDFContextTitle,CFSTR("my pdf file"));

    CFDictionarySetValue(myDic,kCGPDFContextCreator,CFSTR("my name"));

    CFDictionarySetValue(myDic,kCGPDFContextAllowsPrinting,kCFBooleanTrue);   //是否可以打印

    CFDictionarySetValue(myDic,kCGPDFContextAllowsCopying,kCFBooleanFalse); //是否拷贝

    CFDictionarySetValue(myDic,kCGPDFContextUserPassword,CFSTR("123"));       //加密

    CFDictionarySetValue(myDic,kCGPDFContextOwnerPassword,CFSTR("123456"));



    pdfContext = CGPDFContextCreateWithURL(url, &pageRect, myDic);

    CFRelease(myDic);

    CFRelease(url);

    

    pageDic = CFDictionaryCreateMutable(NULL,0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    boxData = CFDataCreate(NULL, (constUInt8 *) &pageRect,sizeof(CGRect));

    CFDictionarySetValue(pageDic,kCGPDFContextMediaBox, boxData);

    

    CGPDFContextBeginPage(pdfContext, pageDic);

    CGImageRef  maskimage = [UIImageimageNamed:@"222.jpg"].CGImage;

    CGContextDrawImage(pdfContext, pageRect, maskimage);

    CGPDFContextEndPage(pdfContext);

    CGContextRelease(pdfContext);

    CFRelease(pageDic);

    CFRelease(boxData);

    

}

Inspecting PDF Document Structure

A PDF document object ( CGPDFDocument ) contains all the information that relates to a PDF document, including its catalog and contents. The entries in the catalog recursively describe the contents of the PDF document. You can access the contents of a PDF document catalog by calling the function  CGPDFDocumentGetCatalog .

A PDF page object (CGPDFPage) represents a page in a PDF document and contains information that relates to a specific page, including thepage dictionary and page contents. You can obtain a page dictionary by calling the function CGPDFPageGetDictionary.

Text

 Text attributes and the functions that control them

Attribute

Function

Specifies

Font

CGContextSetFont

CGContextSelectFont

Typeface.

Font size

CGContextSetFontSize

CGContextSelectFont

Size in text space units.

Character spacing

CGContextSetCharacterSpacing

The amount of extra space (in text space units) between character glyphs.

Text drawing mode

CGContextSetTextDrawingMode

How Quartz renders the individual glyphs onscreen. See Table 16-2 for a list of text drawing modes.

Text matrix

CGContextSetTextMatrix

The transform from text space to user space.

Text position

CGContextSetTextPosition

The location at which text is drawn.

 Text drawing modes

Use this mode

When you want to . . .

Example

kCGTextFill

Perform a fill operation on the text.

Filled text

kCGTextStroke

Perform a stroke operation on the text.

Stroked text.

kCGTextFillStroke

Perform both fill and stroke operations on the text.

Filled and stroked test.

kCGTextInvisible

Get text positions for the purpose of measuring text but not display the text. Note that the text position (xy) is updated, as with all of the drawing modes.

Invisible text.

kCGTextFillClip

Perform a fill operation, then add the text to the clipping area.

Filled text added to the clipping area.

kCGTextStrokeClip

Perform a stroke operation, then add the text to the clipping area.

Stroked text, added to the clipping area

kCGTextFillStrokeClip

Perform both fill and stroke operations, then add the text to the clipping area.

Filled and stroked text, aded to the clipping area

kCGTextClip

Add the text to the clipping area, but do not draw the text.

Test added to the clipping area, but not drawn

Drawing Text

When you use Quartz 2D to draw text, you need to perform these tasks:

  • Set the font and font size.

  • Set the text drawing mode.

  • Set other items as needed—stroke color, fill color, clipping area.

  • Set up a text matrix if you want to translate, rotate, or scale the text space.

  • Draw the text.

文本绘制在开发客户端程序中是一个比较常用的功能,可分为采用控件和直接绘制两种方式。

采用控件的方式比较简便,添加一个比如UILabel对象,然后设置相关属性就好了。但这种方式局限性也比较大。

直接绘制相对比较自由,但也分为使用NSString和Quartz 2D两种方式。

NSString有一组绘制文本的函数,drawAtPoint是其中一个。使用方式如下:

1 NSString* text = @"This is English text(NSString).";
2 [text drawAtPoint:CGPointMake(0, 0) withFont:[UIFont systemFontOfSize:20]];

接口还是比较简单的,也可以画中文。

1 text = @"这是中文文本(NSString)。";
2 [text drawAtPoint:CGPointMake(0, 50) withFont:[UIFont systemFontOfSize:20]];

Quartz 2D中文本绘制稍微复杂一点,因为它提供的接口是C形式的,而不是OC的。先来看看如何画英文:

1 CGContextSetTextMatrix(context, CGAffineTransformMakeScale(1.0, -1.0));
2 CGContextSelectFont(context, "Helvetica", 20, kCGEncodingMacRoman);
3 const char* str = "This is English text(Quartz 2D).";
4 CGContextShowTextAtPoint(context, 0, 100, str, strlen(str));

CGContextSetTextMatrix是调整坐标系,防止文字倒立。
我们用同样的方法尝试绘制中文。

1 const char* str1 = "这是中文文本(Quartz 2D)。";
2 CGContextShowTextAtPoint(context, 0, 150, str1, strlen(str1));

但屏幕上显示的是乱码。为什么呢?

Quartz 2D Programming Guide中有这样一段说明:

To set the font to a text encoding other than MacRoman, you can use the functions CGContextSetFont and CGContextSetFontSize. You must supply a CGFont object to the function CGContextSetFont. You call the function CGFontCreateWithPlatformFont to obtain a CGFont object from an ATS font. When you are ready to draw the text, you use the function CGContextShowGlyphsAtPoint rather than CGContextShowTextAtPoint.

人家说了,如果编码超出MacRoman的范围,你要使用CGContextShowGlyphsAtPoint来绘制。这个函数和CGContextShowTextAtPoint类似,也是5个参数,而且只有第四个参数不同,是字形数组(可能描述的不准确)CGGlyph glyphs[],这个东西如何得到呢?在CoreText frameork(support iOS3.2 and later)提供了这样的接口。代码如下:

复制代码
 1 UniChar *characters;
 2 CGGlyph *glyphs;
 3 CFIndex count;
 4     
 5 CTFontRef ctFont = CTFontCreateWithName(CFSTR("STHeitiSC-Light"), 20.0, NULL);
 6 CTFontDescriptorRef ctFontDesRef = CTFontCopyFontDescriptor(ctFont);
 7 CGFontRef cgFont = CTFontCopyGraphicsFont(ctFont,&ctFontDesRef ); 
 8 CGContextSetFont(context, cgFont);
 9 CFNumberRef pointSizeRef = (CFNumberRef)CTFontDescriptorCopyAttribute(ctFontDesRef,kCTFontSizeAttribute);
10 CGFloat fontSize;
11 CFNumberGetValue(pointSizeRef, kCFNumberCGFloatType,&fontSize);
12 CGContextSetFontSize(context, fontSize);
13 NSString* str2 = @"这是中文文本(Quartz 2D)。";
14 count = CFStringGetLength((CFStringRef)str2);
15 characters = (UniChar *)malloc(sizeof(UniChar) * count);
16 glyphs = (CGGlyph *)malloc(sizeof(CGGlyph) * count);
17 CFStringGetCharacters((CFStringRef)str2, CFRangeMake(0, count), characters);
18 CTFontGetGlyphsForCharacters(ctFont, characters, glyphs, count);
19 CGContextShowGlyphsAtPoint(context, 0, 200, glyphs, str2.length);
20     
21 free(characters);
22 free(glyphs);
复制代码

STHeitiSC-Light是系统自带的一种中文字体。

这样写的话中文就能正常绘制出来了。




你可能感兴趣的:(iphone)