0

我已经尝试了我能想到的一切,但没有一个有效。在 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),图像就会极度倾斜,这没有任何意义。

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

4

0 回答 0