2016-03-20 131 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