【问题标题】:Mask arbitrarily sized UIImageView with resizable UIImage mask使用可调整大小的 UIImage 掩码屏蔽任意大小的 UIImageView
【发布时间】:2013-12-25 12:49:54
【问题描述】:

当前代码:

    self.backgroundImageView.image = [self.message imageOfSize:self.message.size]; // Random image, random size

    UIImage *rightBubbleBackground = [[UIImage imageNamed:@"BubbleRight"]
    resizableImageWithCapInsets:BubbleRightCapInsets
    resizingMode:UIImageResizingModeStretch];

    CALayer *mask = [CALayer layer];
    mask.contents = (id)[rightBubbleBackground CGImage];

    mask.frame = self.backgroundImageView.layer.frame;
    self.backgroundImageView.layer.mask = mask;
    self.backgroundImageView.layer.masksToBounds = YES;

这不能正常工作。尽管应用了遮罩,但 rightBubbleBackground 无法正确调整大小以适应 self.backgroundImageView,即使它设置了调整大小的帽插入 (BubbleRightCapInsets)。

原图:

面具图片(rightBubbleBackground):

结果:

我找到了this answer,但它只适用于对称图像。也许我可以修改这个答案以供我使用。

【问题讨论】:

  • 我认为mask.frame = self.backgroundImageView.layer.frame; 应该是mask.frame = self.backgroundImageView.layer.bounds;。如果图层的框架不等于边界,使用您的代码将导致掩码移动。

标签: ios uiimageview uiimage calayer


【解决方案1】:

我错了。可以修改该答案以适用于不对称图像。我在that answer 上工作了一下,解决了我自己的问题。

以下代码使我的帽子插图适用于遮罩层:

mask.contentsCenter =
CGRectMake(BubbleRightCapInsets.left/rightBubbleBackground.size.width,
BubbleRightCapInsets.top/rightBubbleBackground.size.height,
1.0/rightBubbleBackground.size.width,
1.0/rightBubbleBackground.size.height);

结果:

【讨论】:

  • BubbleRightCapInsets 的值是多少.. 我用这个 UIEdgeInsets BubbleRightCapInsets = UIEdgeInsetsMake(15.0f,20.0f, 15.0f, 20.0f);
  • @MANCHIKANTIKRISHNAKISHORE 我已经重新设计了应用程序,不再记得插图了。不过,您应该为 right 使用更大的值,以考虑箭头,也许 bottom 也是如此。
  • 只需添加它以获得视网膜支持mask.contentsScale = rightBubbleBackground.scale
  • hmm...你用过什么contentsGravity?你如何将图层调整为企鹅图像的大小?您能向我们展示有关内容的整套代码吗?最后,如果图像小于气泡怎么办?然后会发生什么?
  • @ironclap 这太久远了,所以我不记得太多细节了。但我相信contentsGravity 是默认设置。如果图像小于气泡,则图像会拉伸以填充气泡的大小。
【解决方案2】:

我有(部分)同样的问题 - 即像素化图层内容。对我来说,这是通过在 CALayer 上设置 contentsScale 值来解决的——出于某种原因,CALayers 上的默认比例始终为 1.0,即使在 Retina 设备上也是如此。

layer.contentsScale = [UIScreen mainScreen].scale;

另外,如果您正在使用 CAShapeLayer 绘制一个形状,并且想知道它的边缘在视网膜设备上看起来有点锯齿状,请尝试:

shapeLayer.rasterizationScale = [UIScreen mainScreen].scale;
shapeLayer.shouldRasterize = YES;

【讨论】:

    猜你喜欢
    • 2013-01-16
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2013-03-05
    相关资源
    最近更新 更多