Ios 将UIBezierPath转换为UIImage
我正在制作一个苹果手表。所以我附带了一个Iphone应用程序,在这个应用程序中,我使用UIBezierPath绘制了一个饼图。我需要将该图转换为UIImage。以下是我尝试的代码: GraphView.mIos 将UIBezierPath转换为UIImage,ios,objective-c,uiimage,watchkit,uibezierpath,Ios,Objective C,Uiimage,Watchkit,Uibezierpath,我正在制作一个苹果手表。所以我附带了一个Iphone应用程序,在这个应用程序中,我使用UIBezierPath绘制了一个饼图。我需要将该图转换为UIImage。以下是我尝试的代码: GraphView.m rectImage = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 260)]; CGContextRef context = UIGraphicsGetCurrentContext(); UIGraphicsPushCont
rectImage = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 260)];
CGContextRef context = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(context);
UIGraphicsBeginImageContext(rectImage.frame.size);
CGFloat arcRadious = OUTER_RADIOUS;
CGFloat tmpStartAngle = startAngle;
CGFloat tmpEndAngle = endAngle;
UIBezierPath *path = [[UIBezierPath alloc] init];
path.lineWidth = 23;
[path addArcWithCenter:centre radius:arcRadious startAngle:tmpStartAngle endAngle:tmpEndAngle clockwise:YES];
[(UIColor*)_fillColours[index] setStroke];
[path stroke];
CGContextAddPath(context, path.CGPath);
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsPopContext();
UIGraphicsEndImageContext();
但在Apple Watch中,只显示了图表的一部分。谁能告诉我我做错了什么。非常感谢您的帮助。这里有一些地方不对劲,让我们一点一点地把它分解一下。
1:创建上下文 我不完全确定你在这里想做什么 您所做的是从堆栈顶部获取当前上下文(可能根本不存在),然后尝试再次将该上下文推送到堆栈上-这没有意义,因为它已经在堆栈上了(它是当前上下文!) 然后创建图像上下文,它会自动将其推送到堆栈上,使其成为当前上下文 因此我假设你想做的是:
UIGraphicsBeginImageContext(rectImage.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
这将创建一个新的图像上下文,使其成为当前上下文,然后获取对它的引用
2:创建路径 这可能会有问题,因为在添加圆弧之前从未将路径移动到某个点,因此可能无法正确绘制路径 因此,在添加之前,您需要将其移动到圆弧的中心点
UIBezierPath *path = [[UIBezierPath alloc] init];
[path moveToPoint:centre];
[path addArcWithCenter:centre radius:arcRadious startAngle:tmpStartAngle endAngle:tmpEndAngle clockwise:YES];
3:绘制路径 同样,当您调用
UIGraphicsEndImageContext()
时,图像上下文将处理从堆栈中弹出的问题,因此尝试自己弹出它可能会导致问题
最后,一些迂腐的细节。 在这段代码中处理图像时,名称
rectImage
相当容易引起误解,因为它是一个UIView
。我将重命名为rectView
CGFloat arcRadious = OUTER_RADIOUS;
我真诚地希望,OUTER\u RADIOUS
不是宏(\define
)。常量不应使用宏定义-它们不是类型安全的,可能会使调试成为一场噩梦。像躲避瘟疫一样躲避它们
相反,应该使用static
C常量。例如:
static CGFloat const kOuterRadius = 100.0
你能告诉我如何用基于页面的方式在Apple Watch中显示这些图像吗Navigation@JestinSajiChacko请尽量不要在每篇文章中问一个以上的问题——这会产生混乱,通常对未来的读者不利。我会继续问一个关于Apple Watch页面导航的新问题,然后将这个问题回滚到关于在图像上下文中呈现
UIBezierPath
。好的。正如你说的,我问了另一个关于基于页面的导航的问题
[(UIColor*)_fillColours[index] setStroke];
[path stroke];
CGContextAddPath(context, path.CGPath); // <- Remove
UIGraphicsPopContext(); // <- Remove
UIGraphicsEndImageContext();
rectImage = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 260)];
CGFloat arcRadious = OUTER_RADIOUS;
static CGFloat const kOuterRadius = 100.0