Draw ellipse with start and end angle in Objective-C

前端 未结 3 1313
轻奢々
轻奢々 2021-02-09 06:32

I am writing an iPad app in which I am rendering XML objects that represent shapes into graphics on the screen. One of the objects I am trying to render is arcs. Essentially the

3条回答
  •  無奈伤痛
    2021-02-09 06:53

    This category will help.

    #import 
    
    @interface UIBezierPath (OvalSegment)
    
    + (UIBezierPath *)bezierPathWithOvalInRect:(CGRect)rect startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle;
    + (UIBezierPath *)bezierPathWithOvalInRect:(CGRect)rect startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle angleStep:(CGFloat)angleStep;
    
    @end
    
    #import "UIBezierPath+OvalSegment.h"
    
    @implementation UIBezierPath (OvalSegment)
    
    + (UIBezierPath *)bezierPathWithOvalInRect:(CGRect)rect startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle angleStep:(CGFloat)angleStep {
        CGPoint center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
        CGFloat xRadius = CGRectGetWidth(rect)/2.0f;
        CGFloat yRadius = CGRectGetHeight(rect)/2.0f;
    
        UIBezierPath *ellipseSegment = [UIBezierPath new];
    
        CGPoint firstEllipsePoint = [self ellipsePointForAngle:startAngle withCenter:center xRadius:xRadius yRadius:yRadius];
        [ellipseSegment moveToPoint:firstEllipsePoint];
    
        for (CGFloat angle = startAngle + angleStep; angle < endAngle; angle += angleStep) {
            CGPoint ellipsePoint = [self ellipsePointForAngle:angle withCenter:center xRadius:xRadius yRadius:yRadius];
            [ellipseSegment addLineToPoint:ellipsePoint];
        }
    
        CGPoint lastEllipsePoint = [self ellipsePointForAngle:endAngle withCenter:center xRadius:xRadius yRadius:yRadius];
        [ellipseSegment addLineToPoint:lastEllipsePoint];
    
        return ellipseSegment;
    }
    
    + (UIBezierPath *)bezierPathWithOvalInRect:(CGRect)rect startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle {
        return [UIBezierPath bezierPathWithOvalInRect:rect startAngle:startAngle endAngle:endAngle angleStep:M_PI/20.0f];
    }
    
    + (CGPoint)ellipsePointForAngle:(CGFloat)angle withCenter:(CGPoint)center xRadius:(CGFloat)xRadius yRadius:(CGFloat)yRadius {
        CGFloat x = center.x + xRadius * cosf(angle);
        CGFloat y = center.y - yRadius * sinf(angle);
        return CGPointMake(x, y);
    }
    
    @end
    

提交回复
热议问题