【问题标题】:Positioning Pre-made CGPath Inside CGContext在 CGContext 中定位预制的 CGPath
【发布时间】:2012-04-25 22:59:53
【问题描述】:

我正在尝试找出一种方法来添加或附加路径(我已经创建),并且能够以某种方式设置路径的绘制位置。

下面是我所说的一个例子:

//everything here can be compiled in a regular UIViewController
//this example is very trivial but it illustrates basically what I want to do
CGRect preMadeRect = CGRectMake(0.0f, 0.f, 50.f, 50.f);
CGPathRef preMadePath = CGPathCreateWithEllipseInRect(preMadeRect, NULL);

UIGraphicsBeginImageContext(self.view.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();

//I thought that maybe if I moved to a new point
//the path would respect the starting point as its new 
//x and y coordinates
CGContextMoveToPoint(context, 50.f, 50.f);
//I am adding a path
//I want the path to be positioned at new coordinates
//within the context
CGContextAddPath(context, preMadePath);
CGContextStrokePath(context);

UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImageView *imageView = [[UIImageView alloc]initWithImage:resultImage];
[self.view addSubview: imageView];

任何想法将不胜感激。

【问题讨论】:

    标签: ios quartz-2d cgcontext


    【解决方案1】:

    你不能改变路径中的点;他们已经设置好了。但是,您可以对上下文应用变换,改为更改坐标系。

    您的路径定义了一个在原点 (0,0) 有一个角的矩形。默认情况下,原点位于图像的左上角(或左下角)。如果将上下文的坐标系平移 50,50,然后绘制路径(仍然在 0,0),它会出现距离拐角 50 个像素的位置。

    在文档中查找CGContextTranslateCTM

    如果您正在进行其他绘图并需要撤消坐标系更改,您可能还需要使用CGContextSaveGStateCGContextRestoreGState

    【讨论】:

    • CGContextTranslateCTM 只是门票。非常感谢!
    • 额外有趣的事实:如果您开始使用 3D 图形(例如 OpenGL),那么转换坐标系是您完成几乎所有事情的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多