How to mask a square image into an image with round corners in iOS?

前端 未结 8 1704
[愿得一人]
[愿得一人] 2020-11-28 01:20

How can you mask a square image into an image with round corners?

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 02:16

    You can use CoreGraphics to create a path for a round rectangle with this code snippet:

    static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight)
    {
        float fw, fh;
        if (ovalWidth == 0 || ovalHeight == 0) {
            CGContextAddRect(context, rect);
            return;
        }
        CGContextSaveGState(context);
        CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));
        CGContextScaleCTM (context, ovalWidth, ovalHeight);
        fw = CGRectGetWidth (rect) / ovalWidth;
        fh = CGRectGetHeight (rect) / ovalHeight;
        CGContextMoveToPoint(context, fw, fh/2);
        CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);
        CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);
        CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);
        CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);
        CGContextClosePath(context);
        CGContextRestoreGState(context);
    }
    

    And then call CGContextClip(context); to clip it to the rectangle path. Now any drawing done, including drawing an image, will be clipped to the round rectangle shape.

    As an example, assuming "image" is a UIImage, and this is in a drawRect: method:

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    addRoundedRectToPath(context, self.frame, 10, 10);
    CGContextClip(context);
    [image drawInRect:self.frame];
    CGContextRestoreGState(context);
    

提交回复
热议问题