討論CGContextDrawImage


http://www.cnblogs.com/delonchen/archive/2011/06/12/CGContextDrawImage.html

這個函數繪制圖片,但坐標系統原點在左上角,y方向向下的(坐標系A),但在Quartz中坐標系原點在左下角,y方向向上的(坐標系B)。圖片繪制也是顛倒的。

要達到預想的效果必須變換坐標系,代碼如下:

void drawImage(CGContextRef context, CGImageRef image , CGRect rect){

   CGContextSaveGState(context);

 

        CGContextTranslateCTM(context, rect.origin.x, rect.origin.y);//4

        CGContextTranslateCTM(context, 0rect.size.height);//3

        CGContextScaleCTM(context, 1.0, -1.0);//2

        CGContextTranslateCTM(context, -rect.origin.x, -rect.origin.y);//1

        CGContextDrawImage(context, rect, image);

 

        CGContextRestoreGState(context);

}

A到B變換 通過1->2->3->4步驟實現的,這樣好理解些

通常我會用UIImage drawInRect實現想要的功能。

 

 

 

 

我們在使用“CGContextShowTextAtPoint”,經常會遇到字體翻轉問題。CGContextShowTextAtPoint word upside.

這個問題可以通過

 

    CGContextTranslateCTM(ctx, 0, imageSize.height);
    CGContextScaleCTM(ctx, 1, -1);

解決。

不過要是想繼續正常繪制其他內容,我們可以采用先存儲后恢復的方式

 

CGAffineTransform normalState=CGContextGetCTM(context);

    CGContextTranslateCTM(ctx, 0, imageSize.height);
    CGContextScaleCTM(ctx, 1, -1);

 

 CGContextConcatCTM(context, normalState);

 

 

 

- (void)drawRect:(CGRect)rect 
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGContextTranslateCTM(context, 0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    int firstCol = floorf(CGRectGetMinX(rect) / tileSize);
    int lastCol = floorf((CGRectGetMaxX(rect)-1) / tileSize);
    int firstRow = floorf(CGRectGetMinY(rect) / tileSize);
    int lastRow = floorf((CGRectGetMaxY(rect)-1) / tileSize);

    for( int row = firstRow; row <= lastRow; row++ ) 
    {
        for( int col = firstCol; col <= lastCol; col++ ) 
        {
            UIImage = [self getTileWithRow:row column:col];

            CGRect tileRect = CGRectMake((col * tileSize), 
                                         row * tileSize),
                                         tileSize, tileSize);

            CGContextDrawImage(context, tileRect, tile.CGImage);
        }
    }
    CGContextRestoreGState(context);
}

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM