IOS:创建一个带圆角的 UIImage 或 UIImageView

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7705879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:48:03  来源:igfitidea点击:

IOS: create a UIImage or UIImageView with rounded corners

objective-ciosuiimagerounded-corners

提问by cyclingIsBetter

Is it possible create an UIImageor an UIImageViewwith rounded corners? Because I want take an UIImageand show it inside an UIImageView, but I don't know how to do it.

是否可以创建带有圆角的UIImageUIImageView?因为我想拿一个UIImage并在一个里面展示它UIImageView,但我不知道该怎么做。

回答by yinkou

Yes, it is possible.
Import the QuartzCore(#import <QuartzCore/QuartzCore.h>) header and play with the layerproperty of the UIImageView.

对的,这是可能的。
导入QuartzCore#import <QuartzCore/QuartzCore.h>)头部和播放使用layer的财产UIImageView

yourImageView.layer.cornerRadius = yourRadius;
yourImageView.clipsToBounds = YES;

See the CALayerclass reference for more info.

有关更多信息,请参阅CALayer类参考。

回答by Muralikrishna

Try this Code For Round ImageImport QuartzCoreframework simple wayto create Round Image

试试这个代码为圆形图像导入QuartzCore框架 创建圆形图像的简单方法

imageView.layer.backgroundColor=[[UIColor clearColor] CGColor];
imageView.layer.cornerRadius=20;
imageView.layer.borderWidth=2.0;
imageView.layer.masksToBounds = YES;
imageView.layer.borderColor=[[UIColor redColor] CGColor];

enter image description here

在此处输入图片说明

回答by Savas Adar

Objective-C

目标-C

-(UIImage *)makeRoundedImage:(UIImage *) image 
                      radius: (float) radius;
{
  CALayer *imageLayer = [CALayer layer];
  imageLayer.frame = CGRectMake(0, 0, image.size.width, image.size.height);
  imageLayer.contents = (id) image.CGImage;

  imageLayer.masksToBounds = YES;
  imageLayer.cornerRadius = radius;

  UIGraphicsBeginImageContext(image.size);
  [imageLayer renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  return roundedImage;
}

Swift 3

斯威夫特 3

func makeRoundedImage(image: UIImage, radius: Float) -> UIImage {
    var imageLayer = CALayer()
    imageLayer.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
    imageLayer.contents = image.cgImage

    imageLayer.masksToBounds = true
    imageLayer.cornerRadius = radius

    UIGraphicsBeginImageContext(image.size)
    imageLayer.render(in: UIGraphicsGetCurrentContext())
    var roundedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return roundedImage
}

回答by Abdul Rehman Butt

uiimageview.layer.cornerRadius = uiimageview.frame.size.height/2;
uiimageview.clipToBounds = YES;

#import <QuartzCore/QuartzCore.h>

回答by Roman Solodyashkin

// UIImageView+OSExt.h
#import <UIKit/UIKit.h>

@interface UIImageView (OSExt)
- (void)setBorder:(CGFloat)borderWidth color:(UIColor*)color;
@end

// UIImageView+OSExt.m
#import "UIImageView+OSExt.h"

@implementation UIImageView (OSExt)
- (void)layoutSublayersOfLayer:(CALayer *)layer
{
    for ( CALayer *sub in layer.sublayers )
    {
        if ( YES == [sub.name isEqual:@"border-shape"])
        {
            CGFloat borderHalf = floor([(CAShapeLayer*)sub lineWidth] * .5);
            sub.frame = layer.bounds;
            [sub setBounds:CGRectInset(layer.bounds, borderHalf, borderHalf)];
            [sub setPosition:CGPointMake(CGRectGetMidX(layer.bounds),
                                       CGRectGetMidY(layer.bounds))];
        }
    }
}

- (void)setBorder:(CGFloat)borderWidth color:(UIColor*)color
{
    assert(self.frame.size.width == self.frame.size.height);
    for ( CALayer *sub in [NSArray arrayWithArray:self.layer.sublayers] )
    {
        if ( YES == [sub.name isEqual:@"border-shape"])
        {
            [sub removeFromSuperlayer];
            break;
        }
    }

    CGFloat borderHalf = floor(borderWidth * .5);
    self.layer.cornerRadius = self.layer.bounds.size.width * .5;

    CAShapeLayer *circleLayer = [CAShapeLayer layer];
    self.layer.delegate = (id<CALayerDelegate>)self;
    circleLayer.name = @"border-shape";
    [circleLayer setBounds:CGRectInset(self.bounds, borderHalf, borderHalf)];
    [circleLayer setPosition:CGPointMake(CGRectGetMidX(self.layer.bounds),
                                         CGRectGetMidY(self.layer.bounds))];
    [circleLayer setPath:[[UIBezierPath bezierPathWithOvalInRect:circleLayer.bounds] CGPath]];
    [circleLayer setStrokeColor:color.CGColor];
    [circleLayer setFillColor:[UIColor clearColor].CGColor];
    [circleLayer setLineWidth:borderWidth];

    {
    circleLayer.shadowOffset = CGSizeZero;
    circleLayer.shadowColor = [[UIColor whiteColor] CGColor];
    circleLayer.shadowRadius = borderWidth;
    circleLayer.shadowOpacity = .9f;
    circleLayer.shadowOffset = CGSizeZero;
    }

    // Add the sublayer to the image view's layer tree
    [self.layer addSublayer:circleLayer];

    // old variant
    //CALayer *layer = self.layer;
    //layer.masksToBounds = YES;
    //layer.cornerRadius = self.frame.size.width * 0.5;
    //layer.borderWidth = borderWidth;
    //layer.borderColor = color;
}
@end

enter image description here

在此处输入图片说明

回答by orkoden

Setting cornerRadiusand clipsToBoundsis the right way to do this. However if the view's size changes, the radius will not update. In order to get proper resizing and animation behavior, you need to create a UIImageViewsubclass.

设置cornerRadiusclipsToBounds是执行此操作的正确方法。但是,如果视图的大小发生变化,半径将不会更新。为了获得适当的调整大小和动画行为,您需要创建一个UIImageView子类。

class RoundImageView: UIImageView {
    override var bounds: CGRect {
        get {
            return super.bounds
        }
        set {
            super.bounds = newValue
            setNeedsLayout()
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        layer.cornerRadius = bounds.width / 2.0
        clipsToBounds = true
    }
}

回答by Md Rais

Try this to get rounded corners of the image View and also to colour the corners:

试试这个以获得图像视图的圆角并为角着色:

imageView.layer.cornerRadius = imageView.frame.size.height/2;
imageView.layer.masksToBounds = YES;
imageView.layer.borderColor = [UIColor colorWithRed:148/255. green:79/255. blue:216/255. alpha:1.0].CGColor;
imageView.layer.borderWidth=2;

Condition*: The height and the width of the imageView must be same to get rounded corners.

条件*:imageView 的高度和宽度必须相同才能获得圆角。

回答by Manish Mahajan

  1. layer.cornerRadius = imageviewHeight/2

  2. layer.masksToBounds = true

  1. layer.cornerRadius = imageviewHeight/2

  2. layer.masksToBounds = true

回答by Shrawan

Circle with UIBeizerPath #Swift-3 && #imageExtension

用 UIBeizerPath 圈起来 #Swift-3 && #imageExtension

class ViewController: UIViewController {
    @IBOutlet weak var imageOutlet: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        let image = UIImage(named: "IMG_0001.JPG")
        if let image = image {
            let renderimage = image.imageCroppingBezierPath(path: UIBezierPath(arcCenter: CGPoint(x:image.size.width/2,y:image.size.width/2 )  , radius: 200, startAngle: 0, endAngle:  (2 * CGFloat(M_PI) ), clockwise: true) )
                imageOutlet.image = renderimage
        }
    }
}


extension UIImage {
    func imageCroppingBezierPath(path:UIBezierPath) ->UIImage {

        let frame = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)

        //Defining a graphic context  to paint on
        UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)
        //Get the current graphics context (if it exists)
        let context = UIGraphicsGetCurrentContext()
        //save the current graphic context
        context?.saveGState()
        // clipping area
        path.addClip()
        self.draw(in: frame)

        //To extract an image from our canvas
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //restore graphic context
        context?.restoreGState()
        //remove current context from stack
        UIGraphicsEndImageContext()
        return image!
    }
}

回答by helloiloveit

Here how i set my rounded avatar at the center of it contain view:

在这里,我如何将我的圆形头像设置在它的中心包含视图:

-(void)setRoundedAvatar:(UIImageView *)avatarView toDiameter:(float)newSize atView:(UIView *)containedView;
{
    avatarView.layer.cornerRadius = newSize/2;
    avatarView.clipsToBounds = YES;

    avatarView.frame = CGRectMake(0, 0, newSize, newSize);
    CGPoint centerValue = CGPointMake(containView.frame.size.width/2, containedView.frame.size.height/2);
    avatarView.center = centerValue;
}