Ios cgcontext旋转矩形
伙计们! 我需要为CGContext绘制一些图像。这是相关代码:Ios cgcontext旋转矩形,ios,rotation,core-graphics,cgcontext,rect,Ios,Rotation,Core Graphics,Cgcontext,Rect,伙计们! 我需要为CGContext绘制一些图像。这是相关代码: CGContextSaveGState(UIGraphicsGetCurrentContext()); CGContextRef ctx = UIGraphicsGetCurrentContext(); CGRect rect = r; CGContextRotateCTM(ctx, DEGREES_TO_RADIANS(350)); [image drawInRect:r]; CGContextRestoreGStat
CGContextSaveGState(UIGraphicsGetCurrentContext());
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect rect = r;
CGContextRotateCTM(ctx, DEGREES_TO_RADIANS(350));
[image drawInRect:r];
CGContextRestoreGState(UIGraphicsGetCurrentContext());
实际上,矩形是旋转的,并显示在一个区域上,这不是我的目的。我只是想
旋转图像并在同一位置显示。
有什么想法吗?使用以下代码旋转图像 //将度转换为弧度
CGFloat DegreesToRadians(CGFloat degrees)
{
return degrees * M_PI / 180;
};
用drawRect方法编写
// create new context
CGContextRef context = UIGraphicsGetCurrentContext();
// define rotation angle
CGContextRotateCTM(context, DegreesToRadians(45));
// get your UIImage
UIImage *img = [UIImage imageNamed:@"yourImageName"];
// Draw your image at rect
CGContextDrawImage(context, CGRectMake(100, 0, 100, 100), [img CGImage]);
// draw context
UIGraphicsGetImageFromCurrentImageContext();
旋转是关于上下文的原点,即矩形相对于的同一点。如果您在背景中想象一张图表纸,您可以更清楚地看到发生了什么: 该行是窗口/视图/层/上下文的“底部”(y=0)。当然,如果您愿意,您可以在底部下方绘制,如果您的上下文以正确的方式转换,您甚至可以看到它 无论如何,我假设你要做的是相对于一个未旋转的世界旋转矩形,而不是旋转世界和其中的一切 旋转任何东西的唯一方法是旋转世界,因此您需要这样做:
(CGPoint){width/-2.0,height/-2.0}
)-不要使用它以前的原点,因为在转换步骤中已经使用了它
对我来说,首先使用旋转矩阵来计算使图像居中所需的平移量。在下面,我假设您已经将centerX和centerY计算为绘图框的中心,“theta”是您所需的旋转角度(弧度)
let newX = centerX*cos(theta) - centerY*sin(theta)
let newY = centerX*sin(theta) + centerY*cos(theta)
CGContextTranslateCTM(context,newX,newY)
CGContextRotateCTM(context,theta)
<redraw your image here>
设newX=centerX*cos(θ)-centerY*sin(θ)
设newY=centerX*sin(θ)+centerY*cos(θ)
CGContextTranslateCm(上下文,newX,newY)
CGContextRotateCTM(上下文,θ)
对我来说很好。希望能有所帮助。您可能希望尝试用母语键入问题文本,然后使用Google Translate将其转换为英语,因为很难理解您想问的问题。这里还有一个很好的答案-可能与我有类似的问题,我想知道你现在对这个问题有没有解决办法?这与问题中的代码有什么不同?当问题中的代码不存在时,是什么让代码正常工作?我正在使用上下文和imageRef绘制图像,而问题中的图像不存在。使用CGContext和CGImage绘制图像与,总比让UIImage自己画好?我可以用这个逻辑旋转矩形,但一旦我竖起手指,旋转手势结束,矩形就会消失(消失)?有什么想法吗?