【问题标题】:Border on CALayer appears incorrectCALayer 上的边框显示不正确
【发布时间】:2015-04-15 08:46:09
【问题描述】:

我有一个 CALayer,它是一个圆形图像,我正在尝试为此添加一个外部边框。 (阴影在这里对我不起作用)。我已尝试调整 CALAyer 的大小并添加边框,但定位似乎不正确,我不希望形状移动,只需添加边框。

这是我的代码

CGFloat borderWidth = 10.0f;

    CGFloat xPos = cont.layer.frame.origin.x;
    CGFloat yPos = cont.layer.frame.origin.y;
    CGFloat contWidth = cont.layer.frame.size.width;
    CGFloat contHeight = cont.layer.frame.size.width;

    cont.layer.frame = CGRectMake(xPos, yPos, contWidth + borderWidth, contHeight + borderWidth);
    cont.layer.cornerRadius = contWidth / 2;
    cont.layer.borderColor = [[UIColor darkGrayColor] CGColor];
    cont.layer.borderWidth = borderWidth;

提前致谢

【问题讨论】:

  • 不是 100% 确定你在这里做了什么,但是你似乎只在这一行中考虑了边框宽度一次.. cont.layer.frame = CGRectMake(xPos, yPos, contWidth + borderWidth, contHeight + 边框宽度);也许你的意思是 contWidth + borderWidth * 2 或类似的东西,这取决于你想走的路
  • 我已经给出了答案检查它。只需在您的代码下方添加该行。
  • 我的原始图层移动了位置,我希望它保持在同一个地方并且边框出现在外面?
  • 你的答案在哪里?
  • 那么为什么要弄乱框架呢?为什么不直接设置图层的边框宽度、颜色和半径?

标签: ios objective-c xcode border calayer


【解决方案1】:

您的代码是正确的。 请添加一行:

cont.clipsToBounds=YES

self.imgView1.layer.cornerRadius =self.imgView1.frame.size.width / 2;

self.imgView1.layer.borderColor = [[UIColor blueColor] CGColor];

self.imgView1.layer.borderWidth = 0.0f;

self.imgView1.layer.masksToBounds=TRUE;

然后按照以下步骤操作:

  1. 创建另一个 UIImageView 并将其放在第一个 imageView 上方。

  2. 然后将secondImageView的高度和宽度增加到20。

  3. 设置 secondImageView 中心和 FirstImageCenter 相等(在同一点)。

并编写以下代码:

self.imgView2.layer.cornerRadius=self.imgView2.frame.size.width / 2;

self.imgView2.layer.borderColor = [[UIColor blueColor] CGColor];

self.imgView2.layer.borderWidth = 10.0f;

self.imgView2.layer.masksToBounds=TRUE;

请执行以上步骤,它将解决您的问题。

现在你会得到这样的输出:

【讨论】:

  • clipsToBounds 不适用于 CALayer,maskTobounds 可以,但不是我想要的。我的原始图层移动位置,我希望它保持在同一个位置并且边框出现在外面?
  • 我已经使用 clipToBounds 完成了,我将分享屏幕截图
  • 我已将边框颜色设置为蓝色。你需要这个输出或其他任何东西。而 clipToBounds 是 UIImageView 属性。
  • @geoBApp 分享您的屏幕截图
  • 这是我想要实现的,但是边框覆盖了一些图像,我希望它出现在 CALayer(图像)的外部,所以我不会丢失任何图片
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-02
  • 1970-01-01
  • 1970-01-01
  • 2012-12-27
  • 1970-01-01
  • 2010-11-23
  • 2015-01-01
相关资源
最近更新 更多