2011-03-26 105 views
0

我有以下代码,它在调用drawRect时显示图像。在drawRect中旋转UIImage

UIImage *sourceImage = [UIImage imageNamed:@"icon.png"];  


CGRect rect = CGRectMake(12.5, 12.5, 
         sourceImage.size.width, 
         sourceImage.size.height); 

[sourceImage drawInRect:rect]; 

我怎样才能得到这个由多个度旋转,它被绘制之前,一切我读需要它似乎沉重的drawRect中

回答

6
UIImage *image = [UIImage imageNamed:@"icon.png"]; 
UIImageView *imageView = [ [ UIImageView alloc ] initWithFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height) ]; 
imageView.image = image; 
[self addSubview:imageView]; 
CGAffineTransform rotate = CGAffineTransformMakeRotation(1.0/180.0 * 3.14); 
[imageView setTransform:rotate]; 
+2

只有评论:如果没有别的,为了清晰起见,可能最好使用M_PI而不是3.14,如果你设置了一个变换,不要忘记'frame'不应该被使用,而这通常也会阻止正确的界面方向变化时的行为。 – Tommy 2011-03-26 12:36:33

+0

好的,谢谢。 – 2011-03-26 13:03:07

+0

我明白了M_PI的意思,但不是框架。这与我的代码有什么关系? – 2011-03-26 13:06:28

4

旋转ImageView的(或任何其他转型由变换矩阵完成)不是“重”。所有的转换基本上是一个向量和矩阵小的简单乘法(见Apple's Quartz 2D documentation for the math

使用CGContextRotateCTM(context, radians);[sourceImage drawInRect:rect];绘制图像之前。如果您需要围绕另一点旋转图像,请首先使用CGContextTranslateCTM进行翻译。