gpt4 book ai didi

ios - 如何使用 UIBezierPath 创建 UIImage

转载 作者:技术小花猫 更新时间:2023-10-29 10:41:37 26 4
gpt4 key购买 nike

我写了一些代码来创建一个带有 UIBezierPathUIImage 但它没有用。

有人可以帮我找出我的代码有什么问题吗?

-(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

@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

关于ios - 如何使用 UIBezierPath 创建 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17408209/

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