ios 在 UIImageView 周围设置边框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11192190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:56:41  来源:igfitidea点击:

Set border around UIImageView

iphoneobjective-ciosxcode

提问by Girish

I want to apply two types of border on a UIImageView:

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

  1. One is the border on the layerof the UIImageView.
  2. Second is the border around the layerof the UIImageView.
  1. 其一是对边界layerUIImageView
  2. 二是围绕边界layerUIImageView

How can I do this?

我怎样才能做到这一点?

回答by Jonathan King

Try

尝试

#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];

And don't forget to import QuartzCore/QuartzCore.h

并且不要忘记导入 QuartzCore/QuartzCore.h

This example will draw a boarder on the layer, but change it's frame slightly to make the border around the layer.

此示例将在图层上绘制边框,但稍微更改其框架以制作图层周围的边框。

回答by MaxEcho

Another way

其它的办法

You must import

您必须导入

#import <QuartzCore/QuartzCore.h>

Then add code for your UIImageView

然后为您的 UIImageView 添加代码

imgView.clipsToBounds = YES;
imgView.layer.cornerRadius = 8.0;
imgView.layer.borderWidth = 2.0;
imgView.layer.borderColor = [UIColor greenColor].CGColor;

回答by Hugues Duvillier

An other way is to add another layer that goes a bit outside of the UIImageView's layer like so :

另一种方法是添加另一个层,它有点超出 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;