2016-03-20 77 views

回答

7

可以使用QuartzCore功能来创建图像背景,画截取图像,然后描边路径:

- (UIImage *)imageWithBorderAndRoundCornersWithImage:(UIImage *)image lineWidth:(CGFloat)lineWidth cornerRadius:(CGFloat)cornerRadius { 
    UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale); 
    CGRect rect = CGRectZero; 
    rect.size = image.size; 
    CGRect pathRect = CGRectInset(rect, lineWidth/2.0, lineWidth/2.0); 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSaveGState(context); 

    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:pathRect cornerRadius:cornerRadius]; 

    CGContextBeginPath(context); 
    CGContextAddPath(context, path.CGPath); 
    CGContextClosePath(context); 
    CGContextClip(context); 

    [image drawAtPoint:CGPointZero]; 

    CGContextRestoreGState(context); 

    [[UIColor whiteColor] setStroke]; 
    path.lineWidth = lineWidth; 
    [path stroke]; 

    UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    return finalImage; 
} 

这需要:

without border

,使:

enter image description here

-1

需要一个UIImageView以简单的方式做到这一点。圆角(圆角半径)和边框厚度/颜色是UIView的CALayer的典型属性。最简单的方法是有一个UIImageView或者其他类型的UIView来实现它。

类似的东西可能会完成这项工作。

let myImg = UIImage(named: "some_image.png") 
let imgView = UIImageView(image: myImg) 
imgView.clipsToBounds = true 
imgView.layer.cornerRadius = 0.5*imgView.frame.width 
imgView.layer.borderWidth = 5.0 //Or some other value 
imgView.layer.borderColor = UIColor.whiteColor().CGColor 
+0

这会将图像的大小调整为图像视图的大小和设备的缩放比例。这很好,如果这是预期的效果,但OP应该意识到这一点。还要注意的是,这种技术有时会导致沿着圆角的外边缘产生不希望的伪影。你可以通过掩盖图像视图来解决这个问题。请参阅http://stackoverflow.com/a/30125297/1271826。 – Rob