我正在使用Xamarin Forms,我有一个UIImage(在一个自定义渲染器中),我从一个文件中加载它,并将它用作一个模式。该图像是一个4x16像素的图像,其中有两个4x4像素的黑色区域和一个4x8像素的透明区域:
我需要动态地改变黑色区域的颜色。
这是我尝试过的,没有任何成功:
UIImage image = UIImage.FromFile("line_pattern.png");
image = image.ApplyTintColor(UIColor.Orange,UIImageRenderingMode.AlwaysTemplate);
图像加载正确,但颜色没有改变。我该怎么做?
2条答案
按热度按时间xvw2m8pv1#
试着将tintColor设置为imageView:
wf82jlnq2#
设置色调颜色适用于具有单一颜色的PNG。
然而,我们希望能够改变从JPG或PNG加载的
UIImage
对象中的单个颜色,这些对象可能有多种颜色。我们的目标图像是图标或类似的图像,它们的不同颜色数量相对有限,将一种颜色替换为另一种颜色似乎应该很简单,但我们在网上找到的解决方案都没有提供我们所需要的。因此,为了替换颜色,我们创建了以下从
CIColorCube
派生的滤镜类。我们将其用于颜色数量相对有限的图像,但也可以用于更复杂的图像。如果没有得到想要的结果,请尝试使用CubeDimension
和IndexPlusMinus
属性,看看它们对图像的影响。这段代码大致基于Apple Developer Chroma Key Filter Recipe示例。其中用于设置颜色Map表的逻辑可能更适用于照片等复杂图像。
最后,对于从Xamarin更新到MAUI的任何人,只需将一个
nfloat
引用更改为NFloat
,此代码就可以在MAUI上工作。UPDATE:sushihangover/ColorReplaceFilter.cs也可以用来替换颜色。事实上,我们最初尝试使用sushihangover代码,但遇到了问题,所以我们创建了颜色立方体过滤器。最终,我们使用sushihangover过滤器遇到的问题是我们自己造成的;一旦我们弄清楚了这一点,它就能很好地工作。彩色立方体滤镜和Sushihangover滤镜的性能似乎差不多,所以任何一种滤镜都能完成这项工作。