Quartz2D会制图片定位
由于Quartz2D坐标系统Y轴方向是向上的,所以为了不使图片倒立,要对CTM(current transformation matrix)进行变换,其中最重要的就是
1 CGContextScaleCTM(context, 1.0, -1.0);
就是将Y轴到过来,此外还可以进行平移、缩放和旋转,但是经过多次变换以后,最终的显示位置往往和初衷不一致,需要反复的调整。因此我就封装了一个这样的函数,可以比较方便的进行图形绘制。
1 - (void)drawImage:(UIImage*)image 2 inContext:(CGContextRef)context 3 leftBottom:(CGPoint)leftTop 4 scale:(CGFloat)scale 5 rotate:(CGFloat)degree 6 { 7 CGContextSaveGState(context); 8 CGContextTranslateCTM(context, 0, self.bounds.size.height); 9 CGContextScaleCTM(context, 1.0, -1.0); 10 CGContextTranslateCTM(context, leftTop.x, self.bounds.size.height-leftTop.y); 11 if (scale != 1) 12 { 13 CGContextScaleCTM(context, scale, scale); 14 } 15 if(degree != 0) 16 { 17 CGContextRotateCTM(context, degree); 18 } 19 CGRect newRect = CGRectMake(0, 0, image.size.width, image.size.height); 20 CGContextDrawImage(context, newRect, [image CGImage]); 21 CGContextRestoreGState(context); 22 }
调用代码
1 - (void)drawRect:(CGRect)rect 2 { 3 CGContextRef context = UIGraphicsGetCurrentContext(); 4 UIImage *image = [UIImage imageNamed:@"test.jpg"]; 5 [self drawImage:image inContext:context leftBottom:CGPointMake(0, 90) scale:0.5 rotate:0]; 6 [self drawImage:image inContext:context leftBottom:CGPointMake(160, 130) scale:0.6 rotate:0]; 7 [self drawImage:image inContext:context leftBottom:CGPointMake(160, 130) scale:0.7 rotate:-M_PI/3]; 8 [self drawImage:image inContext:context leftBottom:CGPointMake(160, 130) scale:0.8 rotate:-M_PI/3*2]; 9 [self drawImage:image inContext:context leftBottom:CGPointMake(160, 130) scale:0.9 rotate:-M_PI]; 10 [self drawImage:image inContext:context leftBottom:CGPointMake(120, 416) scale:1.0 rotate:0]; 11 }
实现效果