【问题标题】:How to make a region in the centre of a UIImageView transparent如何使 UIImageView 中心的区域透明
【发布时间】:2014-09-04 20:34:53
【问题描述】:

我有一个 UIImageView,我想让图像视图中心的圆形区域透明,这样当图像传递到图像视图时,图像似乎覆盖了除图像视图之外的所有图像视图中心。

这是我目前拥有的 不是图像中的那个黑色圆圈,而是我想看到背景。

有一个类似的问题here,但我需要有人教我如何用代码来做,因为我并不真正了解 Core Graphics。

任何帮助将不胜感激。

【问题讨论】:

  • 为什么不直接使用带有透明孔的 PNG 图像?
  • 因为我是从国外网站拉图片的。我无权访问图片,只有网址
  • 啊,在这种情况下,请参阅this answer on how to create mask。 stackoverflow.com/questions/5757386/how-to-mask-an-uiimageview
  • 蒙版是否需要与图像的大小完全相同?
  • 核心图形IS代码。除了首先获得具有透明中心的图像之外,没有其他方法可以做到这一点。这将是最简单的。

标签: ios objective-c uiimageview xcode5 core-graphics


【解决方案1】:

斯威夫特 5

let maskPath = UIBezierPath(ovalIn: albumImageView.bounds)
    let holePath = UIBezierPath(ovalIn: albumImageView.bounds.insetBy(dx: 30,dy: 30))
    maskPath.append(holePath)
    let mask = CAShapeLayer()
    mask.fillRule = .evenOdd
    mask.path = maskPath.cgPath
    albumImageView.layer.mask = mask

【讨论】:

    【解决方案2】:

    这样就可以了:

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50.0, 50.0, 100.0, 100.0)];
    [imageView setBackgroundColor:[UIColor redColor]];
    
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithOvalInRect:imageView.bounds];
    
    UIBezierPath *holePath = [UIBezierPath bezierPathWithOvalInRect:CGRectInset(imageView.bounds, 35.0, 35.0)];
    [maskPath appendPath:holePath];
    
    CAShapeLayer *mask = [CAShapeLayer layer];
    [mask setFillRule:kCAFillRuleEvenOdd];
    mask.path = maskPath.CGPath;
    
    [imageView.layer setMask:mask];
    
    [self.view addSubview:imageView];
    

    你给'holePath'的插图越多,内圆的半径就越小;)

    【讨论】:

    • 工作就像一个魅力!谢谢
    • 没问题 :) 看起来您要在 tableView 中使用 imageView ?如果是这样 - 掩蔽可能不利于滚动性能。要解决这个问题,请将 imageView 图层的“shouldRasterize”设置为 YES,并将“rasterizationScale”设置为“[UIScreen mainScreen].scale”
    • 它是一个搜索功能,我将搜索结果的数量限制为 10 个,因此表格视图几乎不能滚动,因此不会注意到开销。但感谢您的提醒。我一定会记下这一点以备将来使用。
    猜你喜欢
    • 2015-01-08
    • 1970-01-01
    • 2011-05-21
    • 2012-06-20
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    相关资源
    最近更新 更多