iOS:创建带有圆角的UIImage或UIImageView


Answers:


235

是的,有可能。
导入QuartzCore#import <QuartzCore/QuartzCore.h>)标头并使用的layer属性UIImageView

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

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


1
好的,它可以用于UIImageView,但是如果我在UIImageView中放入一个UIImage不起作用,该如何解决?
cyclingIsBetter

9
不要忘记激活clipToBoundsyourImageView.clipsToBounds = YES;
yinkou 2011年

1
如果ImageView在scrollView或tableView单元格内,则clipsToBounds会使滚动性能变差。
OzBoz

我这样测试!消耗大量内存!
LE SANG 2015年

我在Swift 2.0中使用了这段代码,它工作正常,谢谢。顺便说一句,我确实将YES更改为。
lmiguelvargasf 2015年

54

尝试使用此代码进行圆形图像导入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];

在此处输入图片说明


47

物镜

-(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;
}

迅捷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
}

如何使图像中心部分产生细长的曲线形状如何实现这个概念,请让我知道客观的C语言
Ramani Hitesh 18-3-27

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

#import <QuartzCore/QuartzCore.h>

2
这与其他答案有何不同?
mmmmmm 2013年

3
@Mark uiimageview.frame.size.height/2;是真正的宝石,可以使图像完美地形成一个完整的圆形。
2015年

您如何提出uiimageview.frame.size.height / 2?你能解释一下吗?
Idrees Ashraf 2015年

@IdreesAshraf这里涉及一个简单的逻辑..半高的半径将从顶部中间开始到左侧中间。使弧度为45度。因此在4个侧面上都具有这样的弧线将使视图形成完美的圆圈。
Ans 2015年

1
@Ans如果我使用宽度和高度不同的图像,它将失败。您可以尝试..
Idrees Ashraf

3
// 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

在此处输入图片说明


看起来图像中的一点点流过了边框。我不确定是否有一个简单的解决方法……
约翰·吉布

边界得到改善
Roman Solodyashkin

2

设置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
    }
}

1

尝试以下操作以获取图像视图的圆角并为这些角着色:

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;

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



0

可以,但是我建议您创建带有圆角的透明png图像(遮罩),然后使用UIImageView将其放置在图像上。这可能是更快的解决方案(例如,如果您需要动画或滚动)。


0

在这里,我如何将我的圆形化身设置在其中心包含视图:

-(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;
}

0

与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!
    }
}

-1
# import QuartzCore framework
imageView.layer.cornerRadius=imgvwUser.frame.size.width/2;
imageView.layer.masksToBounds = YES;

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.