如何使用UIBezierPath创建UIImage [英] How to create a UIImage with UIBezierPath
本文介绍了如何使用UIBezierPath创建UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一些代码,用 UIBezierPath
创建一个 UIImage
,但它没有用。
有人可以帮我找出我的代码有什么问题。
I wrote some code to create a UIImage
with UIBezierPath
but it didn't work.
Can someone help me find out what's wrong with my code.
-(UIImage*) drawTriangle{
CGRect rect = CGRectMake(0.0, 0.0, 30.0, 30.0);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(context);
UIBezierPath *bezier = [UIBezierPath bezierPathWithRect:rect];
[bezier moveToPoint:CGPointMake(25, 5)];
[bezier addLineToPoint:CGPointMake(5, 15)];
[bezier addLineToPoint:CGPointMake(25, 25)];
[bezier setLineWidth:3.0];
[bezier setLineJoinStyle:kCGLineJoinBevel];
[bezier stroke];
CGContextAddPath(context, bezier.CGPath);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsPopContext();
UIGraphicsEndImageContext();
return image;
}
推荐答案
将此类别尝试为UIBezierPath
try this category to UIBezierPath
@interface UIBezierPath (Image)
/** Returns an image of the path drawn using a stroke */
-(UIImage*) strokeImageWithColor:(UIColor*)color;
@end
@implementation UIBezierPath (Image)
-(UIImage*) strokeImageWithColor:(UIColor*)color {
// adjust bounds to account for extra space needed for lineWidth
CGFloat width = self.bounds.size.width + self.lineWidth * 2;
CGFloat height = self.bounds.size.height + self.lineWidth * 2;
CGRect bounds = CGRectMake(self.bounds.origin.x, self.bounds.origin.y, width, height);
// create a view to draw the path in
UIView *view = [[UIView alloc] initWithFrame:bounds];
// begin graphics context for drawing
UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, [[UIScreen mainScreen] scale]);
// configure the view to render in the graphics context
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
// get reference to the graphics context
CGContextRef context = UIGraphicsGetCurrentContext();
// translate matrix so that path will be centered in bounds
CGContextTranslateCTM(context, -(bounds.origin.x - self.lineWidth), -(bounds.origin.y - self.lineWidth));
// set color
[color set];
// draw the stroke
[self stroke];
// get an image of the graphics context
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
// end the context
UIGraphicsEndImageContext();
return viewImage;
}
@end
这篇关于如何使用UIBezierPath创建UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文