将方形70 * 70px剪裁成正方形

时间:2015-02-18 09:15:41

标签: ios objective-c xcode uiimage

在我使用以下代码制作UIImage通告之前:

image.layer.cornerRadius = button.frame.size.width / 2;
image.clipsToBounds = YES;

图像大小为70 * 70px,我想在CGImageContext中执行相同操作并保存结果,而不是像上面那样设置角半径,因为这会大大降低UI的速度。无论如何在CGImageContext中执行此操作?感谢

2 个答案:

答案 0 :(得分:1)

您可以设置圆角蒙版而不是圆角,这会降低效果。

夫特:

let roundMaskLayer = CAShapeLayer()
roundMaskLayer.path = UIBezierPath(roundedRect: self.YOURIMAGEVIEW.bounds, byRoundingCorners: UIRectCorner.AllCorners, cornerRadii: CGSize(width: self.YOURIMAGEVIEW.frame.size.width/2,height: self.YOURIMAGEVIEW.frame.size.height/2)).CGPath
self.YOURIMAGEVIEW.layer.mask = roundMaskLayer
self.YOURIMAGEVIEW.layer.masksToBounds = true

目标-C:

CAShapeLayer *roundMaskLayer = [[CAShapeLayer alloc] init];
roundMaskLayer.path = (__bridge CGPathRef)([UIBezierPath bezierPathWithRoundedRect:self.YOURIMAGEVIEW.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(self.YOURIMAGEVIEW.bounds.size.width/2, self.YOURIMAGEVIEW.bounds.size.height/2)]);
self.YOURIMAGEVIEW.layer.mask = roundMaskLayer;
self.YOURIMAGEVIEW.layer.masksToBounds = true;

答案 1 :(得分:1)

如果你想渲染和保存;如果屏蔽不够高,那么这个片段就可以做到。

+(UIImage *)roundedImage:(UIImage *)image dimension:(CGFloat)dimension {

    UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, dimension, dimension)];
    imageview.layer.cornerRadius = dimension/2;
    imageview.clipsToBounds = YES;
    imageview.image = image;
    imageview.contentMode = UIViewContentModeScaleAspectFill;

    UIGraphicsBeginImageContextWithOptions(imageview.bounds.size, NO, 0);
    [imageview drawViewHierarchyInRect:imageview.bounds afterScreenUpdates:YES];
    UIImage *renderedRound = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return renderedRound;

}