CoreGraphics在iOS中的一个点周围旋转和成像

时间:2012-12-10 15:07:52

标签: ios core-graphics transform

我已经尝试了所有我能想到的东西,但没有任何工作。在iOS UIView drawRect中,我需要一个函数来获取图像,图像上的点,比例和角度,并绘制围绕视图中心的给定点旋转的图像。因此,如果我想围绕原点(0,0)旋转,我的图像边缘将出现在视图的中心。

这是我的第一个代码版本:

-(void)drawImage:(UIImage*)image atAngle:(float)theta atScale:(float)scale whereCenter:(JBPoint*)center inContext:(CGContextRef)context
{
    UIGraphicsPushContext(context);

    //Rotate
    CGContextTranslateCTM (context, -center.x, -center.y);
    CGContextRotateCTM (context, theta);
    CGContextTranslateCTM (context, center.x, center.y);

    //Scale
    CGContextScaleCTM(context, scale, scale);

    //Draw
    GContextDrawImage(context, self.frame, image.CGImage);

    UIGraphicsPopContext();

}

然而,这使图像偏斜,使得它不是仿射变换,即使我只对其进行了仿射变换。

在摆弄它一段时间之后,我决定手动完成它,并计算四个角点的位置然后绘制它:

-(void)drawImage:(UIImage*)image atAngle:(float)theta atScale:(float)scale whereCenter:(JBPoint*)center inContext:(CGContextRef)context
{
    UIGraphicsPushContext(context);

    CGContextRotateCTM (context, theta);

    float ux = cos(theta);
    float uy = sin(theta);
    float vx = sin(theta);
    float vy = -cos(theta);

    CGPoint p1 = CGPointMake(self.frame.size.width/2.0f-ux*scale*center.x-vx*scale*(image.size.height - center.y), self.frame.size.height/2.0f-uy*scale*center.x-vy*scale*(image.size.height - center.y));
    CGPoint p2 = CGPointMake(p1.x+ux*image.size.width*scale, p1.y+uy*image.size.width*scale);
    CGPoint p3 = CGPointMake(p2.x+vx*image.size.height*scale, p2.y+vy*image.size.height*scale);
    CGPoint p4 = CGPointMake(p1.x+vx*image.size.height*scale, p1.y+vy*image.size.height*scale);

    //Sanity check. These all should be the same since I want to center at the center of the frame
    NSLog(@"Center: %f, %f", (p1.x+p3.x)/2.0f, (p1.y+p3.y)/2.0f);
    NSLog(@"Center: %f, %f", (p2.x+p4.x)/2.0f, (p2.y+p4.y)/2.0f);
    NSLog(@"Center: %f, %f", self.frame.size.width/2.0f, self.frame.size.height/2.0f);

    float minX = MIN(MIN(p1.x, p2.x), MIN(p3.x, p4.x));
    float minY = MIN(MIN(p1.y, p2.y), MIN(p3.y, p4.y));

    float maxX = MAX(MAX(p1.x, p2.x), MAX(p3.x, p4.x));
    float maxY = MAX(MAX(p1.y, p2.y), MAX(p3.y, p4.y));

    CGContextSetAlpha(context, alpha);
    CGContextScaleCTM(context, 1, -1);

    CGContextDrawImage(context, CGRectMake(minX, -minY, (maxX-minX), -(maxY-minY)), image.CGImage);
    UIGraphicsPopContext();
}

这适用于角度为0,但只要角度变为90度(pi / 2),图像就会非常歪斜,这没有任何意义。

这似乎是一个如此简单的问题。为什么这么难?有谁看到我做错了什么?

0 个答案:

没有答案