【问题标题】:How to mask WKInterfaceImage programmatically如何以编程方式屏蔽 WKInterfaceImage
【发布时间】:2015-09-08 15:03:30
【问题描述】:

我曾经在iOS中使用下面的代码来屏蔽UIImageView

#import <QuartzCore/QuartzCore.h>

profilePhoto.layer.masksToBounds = YES;
profilePhoto.layer.cornerRadius = profilePhoto.bounds.size.width/2;

结果如下:

有人知道如何为WKInterfaceImage 做同样的事情吗?

【问题讨论】:

    标签: objective-c watchkit quartz-core


    【解决方案1】:

    您需要使用 Core Graphics 将您的图像绘制成一个圆形,然后将该图像设置为 WKInterfaceImage。请参阅这篇文章,了解如何使用 Core Graphics 绘制带有圆形地图的图像。 How to mask a square image into an image with round corners in the iPhone SDK?

    这是从其他 SO 帖子复制的代码,并稍作修改以将图像剪裁成一个圆圈。 (我还没有运行此代码,所以它可能存在一些问题。它应该让你接近。)

    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);
    }
    
    UIImage* img = <My_Image_To_Draw?
    UIGraphicsBeginImageContextWithOptions(img.size, NO, 2.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGRect rect = CGRectMake(0,0,img.size.width, img.size.height);
    addRoundedRectToPath(context, rect, img.size.width, img.size.height);
    CGContextClip(context);
    [image drawInRect:rect];
    UIImage* imageClippedToCircle = UIGraphicsGetImageFromCurrentImageContext();
    CGContextRestoreGState(context);
    
    //Now you can use imageClippedToCircle
    

    【讨论】:

    • 能否请您用一段代码详细说明,因为我仍然无法将答案中的代码映射到手表套件
    • 感谢@Stephen 成功了,我只需要修改对addRoundedRectToPath(context, rect, img.size.width/2.0, img.size.height/2.0); 的调用即可将照片剪辑成一个圆圈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 2011-06-30
    • 2015-02-26
    • 2011-07-12
    • 2016-11-14
    • 2011-02-09
    • 1970-01-01
    相关资源
    最近更新 更多