CGContextRotateCTM无法旋转UIImage

时间:2015-07-08 04:22:32

标签: ios core-graphics

我想绘制一个删除按钮,就像主屏幕上的删除应用按钮一样,如下面的代码。

首先绘制十字架,然后旋转45度。我的代码出了什么问题?

self.deleteButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, BADGE_SIZE, BADGE_SIZE)];

if (!deleteBtnImg) {
    CGRect imgFrame = self.deleteButton.bounds;

    UIGraphicsBeginImageContextWithOptions(imgFrame.size, NO, 0.0);

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);

    CGFloat size = MIN(imgFrame.size.width, imgFrame.size.height);
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(imgFrame.size.width/2, imgFrame.size.height/2)
                                                        radius:size/2-RADIUS_MARGIN
                                                    startAngle:0
                                                      endAngle:M_PI * 2
                                                     clockwise:YES];
    [path moveToPoint:CGPointMake(size / 2, 0)];
    [path addLineToPoint:CGPointMake(size / 2, size)];
    [path moveToPoint:CGPointMake(0, size / 2)];
    [path addLineToPoint:CGPointMake(size, size / 2)];
    [[UIColor whiteColor] setFill];
    [[UIColor redColor] setStroke];
    [path setLineWidth:1.0];
    [path fill];
    [path stroke];

    CGContextRotateCTM(context, M_PI/4);

    deleteBtnImg = UIGraphicsGetImageFromCurrentImageContext();
    CGContextRestoreGState(context);
    UIGraphicsEndImageContext();
}
[self.deleteButton setImage:deleteBtnImg forState:UIControlStateNormal];

1 个答案:

答案 0 :(得分:5)

您必须在开始绘图之前旋转上下文。但即使您在绘图前旋转。图像看起来仍然不正确。这是因为当您旋转上下文时,上下文实际上是围绕它的原点旋转(0,0)或左下角(CoreGraphic的坐标系与UI略有不同)。因此,您可以做的是,在旋转之前,转换上下文以使其围绕其中心旋转,然后在旋转后将其移回。这是一个简单的例子:

Name