17

我想在 a 上应用两种类型的边框UIImageView

  1. layer一个是的边界UIImageView
  2. 二是周边的layer边界UIImageView

我怎样才能做到这一点?

4

4 回答 4

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

这个例子将在图层上绘制一个边框,但稍微改变它的框架以在图层周围制作边框。

于 2012-06-25T18:16:58.667 回答
9

其他方式

您必须导入

#import <QuartzCore/QuartzCore.h>

然后为您的 UIImageView 添加代码

imgView.clipsToBounds = YES;
imgView.layer.cornerRadius = 8.0;
imgView.layer.borderWidth = 2.0;
imgView.layer.borderColor = [UIColor greenColor].CGColor;
于 2015-04-09T09:39:53.073 回答
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;
于 2015-11-10T06:00:43.790 回答
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
于 2020-10-16T09:02:57.457 回答