Double colored border for UIImageView

2019-05-30 03:54发布

I would like to setup an image with 2 borders around it. Is it possible to duplicate the borderWidth property on the same image view somehow? Like this:

   // inner circle/border
   self.avatar.layer.borderWidth = 2.0f;
   // outer circle/border
   self.avatar.layer.borderWidth = 4.0f;

  UIColor *myColor = [UIColor colorWithRed:(24.0 / 255.0) green:(169.0 / 255.0) blue:(250.0 / 255.0) alpha: 1];
  UIColor *myColor2 = [UIColor colorWithRed:(24.0 / 255.0) green:(169.0 / 255.0) blue:(20.0 / 255.0) alpha: 1];
   self.avatar.layer.borderColor = myColor.CGColor;
   self.avatar.layer.borderColor = myColor2.CGColor;

Unfortunately this code doesn't work, but if there is any solution that's easy like this I would be very happy with it. Actually my only idea is to duplicate the UIImageView, put it under the "real" image and set border for it. This way would work, but I need a cleaner solution.

1条回答
神经病院院长
2楼-- · 2019-05-30 04:10

For that you can add your UIImageView inside a UIView and set the layer of that UIView.

You can do it like:

self.avatar.layer.borderWidth = 2.0f;
UIColor *myColor   = [UIColor colorWithRed:(24.0 / 255.0) green:(169.0 / 255.0) blue:(250.0 / 255.0) alpha: 1];
UIColor *myColor2  = [UIColor colorWithRed:(24.0 / 255.0) green:(169.0 / 255.0) blue:(20.0 / 255.0) alpha: 1];
CGPoint point      = self.avatar.frame.origin;
CGFloat width      = self.avatar.frame.size.width;
CGFloat height     = self.avatar.frame.size.height;
UIView *holderView = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, width+4, height+4)];

holderView.layer.borderWidth  = 2.0;
self.avatar.layer.borderColor = myColor.CGColor;
holderView.layer.borderColor  = myColor2.CGColor;
[self.avatar setFrame:CGRectMake(2, 2, width, height)];
[holderView addSubview:self.avatar];
[self.view addSubview:holderView];

Or you can add a new CALayer as a sublayer of your existing layer to do this.

查看更多
登录 后发表回答