【问题标题】:iOS - Set ImageView background color and maskiOS - 设置 ImageView 背景颜色和遮罩
【发布时间】:2018-01-06 06:42:37
【问题描述】:

如何为图标设置 ImageView 的背景颜色并将其遮罩到边界?那么图像的内部透明部分就是背景色?

示例:在这个 twitter 图标中,如何将图标的内部白色(透明)部分设置为不同的颜色?

编辑:如果图像不是圆形怎么办?但任何形状。

【问题讨论】:

  • 设置背景颜色、圆角半径和遮罩。
  • 检查我更新的答案是否是你想要的

标签: ios swift swift3 uiimageview


【解决方案1】:

您必须按照以下步骤操作

    imageView.image = UIImage(named: "yourImageName")?.withRenderingMode(.alwaysOriginal)
    imageView.layer.cornerRadius = 14 //number of your choice
    imageView.layer.masksToBounds = true
    imageView.tintColor = .black

【讨论】:

  • 我觉得不需要设置渲染模式
  • 图片不是圆形怎么办
  • 正如 Phyber 所建议的,您可以在这里设置任何值,如果您不想要圆角或圆形,您可以将cornerRadius 设为 0
【解决方案2】:
imageView.backgroundColor = .blue //Sets the background color
imageView.layer.cornerRadius = imageView.width/2   //Crops the image to be a circle
imageView.layer.masksToBounds = true //Sets the mask to bounds

如果您想要自定义形状,可以这样做:

  • 创建两个图像视图(在彼此之上)
  • 第一个 imageView 照常使用
  • 第二个 imageView 用作背景形状

前台代码

firstImageView.backgroundColor = .clear

第二个 imageView(在后台)

secondImageView.image = UIImage(named: "yourImage").withRenderingMode(.alwaysTemplate)
secondImageView.tintColor = yourBackgroundColor
secondImageView.backgroundColor = .clear

【讨论】:

  • 但如果不是圆形怎么办
  • 你可以设置任何你想要的圆角半径。
  • 但如果您想要自定义形状,您可以使用两个图像。一种用于形状和背景,一种用于前景。
猜你喜欢
  • 1970-01-01
  • 2015-03-23
  • 1970-01-01
  • 2023-03-18
  • 2022-11-01
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多