gpt4 book ai didi

iphone - 在 Quartz 中从椭圆中心绘制径向线

转载 作者:行者123 更新时间:2023-12-03 21:19:15 24 4
gpt4 key购买 nike

我正在尝试从 quartz 椭圆的中心绘制径向线。

CGContextSetRGBStrokeColor(ctx, 0.0, 1.0, 1.0, 1.0); //cyan stroke
CGContextSetLineWidth(ctx, 2.0);
CGContextFillEllipseInRect(ctx, oRect);

CGContextSaveGState(ctx);

CGPoint center = CGPointMake(CGRectGetMidX(oRect), CGRectGetMidY(oRect));
CGFloat maxX = CGRectGetMaxX(oRect);

for(int i = 0; i < 5; i++) {
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, maxX, center.y);
CGContextAddLineToPoint(ctx, center.x, center.y);
CGContextClosePath(ctx);
CGContextStrokePath(ctx);
CGContextRotateCTM(ctx, degreesToRadians(5.0));
}


CGContextRestoreGState(ctx);

结果: quartz result

它不是从椭圆中心发出的线条图,而是随着矩阵的每次变换而移动。为什么中心重置而不是旋转?

最佳答案

很简单,这是因为 CGContextRotateCTM(ctx, DegreesToRadians(5.0)); 调用围绕坐标系的原点应用了旋转矩阵。在这种情况下,原点似乎位于 View 的左上角。整个物体围绕左上角旋转,而不是围绕你的视野中点旋转。

如果您想围绕 View 中心旋转,则需要首先移动坐标系。最简单的方法可能就是应用平移将其移至中心,应用旋转,然后应用另一个平移将其移回角落。它最终会看起来像这样:

///...
CGPoint center = CGPointMake(CGRectGetMidX(oRect), CGRectGetMidY(oRect));
CGFloat maxX = CGRectGetMaxX(oRect);

for(int i = 0; i < 5; i++) {
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, maxX, center.y);
CGContextAddLineToPoint(ctx, center.x, center.y);
CGContextClosePath(ctx);
CGContextStrokePath(ctx);
CGContextTranslateCTM(ctx, center.x, center.y); // Note
CGContextRotateCTM(ctx, degreesToRadians(5.0));
CGContextTranslateCTM(ctx, -center.x, -center.y); // Note
}

当然,您可以将整个翻译-旋转-翻译操作集中到一个 CGAffineTransform 中,如下所示:

// Outside the loop
CGAffineTransform transform = CGAffineTransformMakeTranslation(center.x, center.y);
transform = CGAffineTransformRotate(transform, degreesToRadians(5.0));
transform = CGAffineTransformTranslate(transform, -center.x, -center.y);

for(int i = 0; i < 5; i++) {
// ...
CGContextConcatCTM(ctx, transform);
}

这将为您节省每次循环执行三个单独的矩阵运算时的性能损失。但请选择您更清楚的一个;除非您看到对性能有可衡量的影响,否则总是更喜欢可维护性。

关于iphone - 在 Quartz 中从椭圆中心绘制径向线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6529845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com