How to create a UIImage with UIBezierPath

前端 未结 7 868
南旧
南旧 2020-12-09 06:02

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?

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-09 06:23

    Your usage would be:

    UIBezierPath *path = [UIBezierPath trianglePathWithSize: CGSizeMake(50, 50)];
                  path.lineWidth = 2;
    
    UIImage *image = [path imageWithStrokeColor: [UIColor blueColor] 
                                      fillColor: [UIColor redColor]];
    

    Category to create bezier path shapes:

    @implementation UIBezierPath (Shapes)
    
    + (UIBezierPath *) trianglePathWithSize: (CGSize) size;
    {
        UIBezierPath *result = [UIBezierPath bezierPath];
        result.lineJoinStyle = kCGLineJoinMiter;
    
        [result moveToPoint: CGPointMake(0, 0)];
        [result addLineToPoint: CGPointMake(size.width, size.height / 2)];
        [result addLineToPoint: CGPointMake(0, size.height)];
        [result closePath];
    
        return result;
    }
    
    @end
    

    Category to take any path and render in UIImage from it:

    @implementation UIBezierPath (UIImage)
    
    - (UIImage *) imageWithStrokeColor: (UIColor *) strokeColor fillColor: (UIColor *) 
    
    fillColor;
    {
        CGRect bounds = self.bounds;
    
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(bounds.size.width + self.lineWidth * 2, bounds.size.width + self.lineWidth * 2),
                                               false, [UIScreen mainScreen].scale);
    
        CGContextRef context = UIGraphicsGetCurrentContext();
    
        // offset the draw to allow the line thickness to not get clipped
        CGContextTranslateCTM(context, self.lineWidth, self.lineWidth);
    
        if (!strokeColor)
        {
            strokeColor = fillColor;
        }
        else
        if (!fillColor)
        {
            fillColor = strokeColor;
        }
    
        [strokeColor setStroke];
        [fillColor setFill];
    
        [self fill];
        [self stroke];
    
        UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    
        UIGraphicsEndImageContext();
    
        return result;
    }
    
    @end
    

提交回复
热议问题