我想在UIImageView
上应用两种类型的边框:
layer
的{{1}}边框。UIImageView
的{{1}}周围的边框。我该怎么做?
答案 0 :(得分:32)
尝试
#define kBorderWidth 3.0
#define kCornerRadius 8.0
CALayer *borderLayer = [CALayer layer];
CGRect borderFrame = CGRectMake(0, 0, (imageView.frame.size.width), (imageView.frame.size.height));
[borderLayer setBackgroundColor:[[UIColor clearColor] CGColor]];
[borderLayer setFrame:borderFrame];
[borderLayer setCornerRadius:kCornerRadius];
[borderLayer setBorderWidth:kBorderWidth];
[borderLayer setBorderColor:[[UIColor redColor] CGColor]];
[imageView.layer addSublayer:borderLayer];
不要忘记导入QuartzCore / QuartzCore.h
此示例将在图层上绘制一个边框,但稍微更改它的边框以在图层周围创建边框。
答案 1 :(得分:8)
另一种方式
您必须导入
#import <QuartzCore/QuartzCore.h>
然后为您的UIImageView添加代码
imgView.clipsToBounds = YES;
imgView.layer.cornerRadius = 8.0;
imgView.layer.borderWidth = 2.0;
imgView.layer.borderColor = [UIColor greenColor].CGColor;
答案 2 :(得分:2)
另一种方法是添加另一个在UIImageView的图层之外的图层,如下所示:
CALayer * externalBorder = [CALayer layer];
externalBorder.frame = CGRectMake(-1, -1, myView.frame.size.width+2, myView.frame.size.height+2);
externalBorder.borderColor = [UIColor blackColor].CGColor;
externalBorder.borderWidth = 1.0;
[myView.layer addSublayer:externalBorder];
myView.layer.masksToBounds = NO;
答案 3 :(得分:0)
快捷键5
使用 UIImageView 时 当心 ; masksToBounds = false
表示图像会溢出
let outsideBorder = CALayer()
outsideBorder.frame = CGRect(x: -1, y: -1, width: myView.frame.size.width+2, height: myView.frame.size.height+2)
outsideBorder.borderColor = UIColor.black.cgColor
outsideBorder.borderWidth = 1.0
myView.layer.addSublayer(outsideBorder)
myView.masksToBounds = false