如何将Android.Graphics中GetPixel方法返回的Int转换为Color?

3

我想要获取Bitmap中像素的颜色。通常情况下,我使用GetPixel(x,y)方法来实现。但是在Android.Graphics中,该方法返回一个表示颜色的int类型值。因此,我需要知道如何从这个整数值中获取颜色。

事实上,这正是我最终要做的(在mPlan中去除白色):

for (int x=0; x <  PlanWidth; x++)
{
    for (int y=0; y <  PlanHeight; y++)
    {
        if (mPlan.GetPixel(x, y) ==  Color.White)                    
            mPlan.SetPixel(x, y, (Color.White - mPlan.GetPixel(x, y)));
    }
}

当前代码有问题吗?在Java中,它将是完全正确的,因为Color.White是int。 - Sergey Glotov
“白色去除”是什么意思?您是想从位图中删除每个白色像素吗?还是只想让每个像素变暗? - yan yankelevich
1
Color.White.ToArgb()? 您可以将 Color.White 转换为整数,而不是每次使用 GetPixel() 方法获取结果。 - Sergey Glotov
@SergeyGlotov 我试过了,但是 GetPixel(x,y) 给出的整数不是 Argb,所以我无法恢复结果颜色然后将其设置在像素中。 - dou
1
如果不是ARGB,GetPixel()返回什么?我在文档中查找,它说“返回的颜色是非预乘的ARGB值。” - Sergey Glotov
显示剩余5条评论
2个回答

3

Android.Graphics.Color有一个构造函数Color(Int32)。要将int转换为Color,您可以像这样做:

new Color(mPlan.GetPixel(x, y)) ==  Color.White

我认为更好的做法是使用Color.White.ToArgb()Color.White转换为整数,并将SetPixel()的参数替换为Color.Black,因为Color.White - Color.White将得到Color.Black

int white = Color.White.ToArgb();
for (int x=0; x < PlanWidth; x++)
{
    for (int y=0; y < PlanHeight; y++)
    {
        if (mPlan.GetPixel(x, y) ==  white)                    
            mPlan.SetPixel(x, y, Color.Black);
    }
}

是的,但SetPixel需要一个颜色作为第三个参数而不是整数。我不知道如何恢复颜色。 Color.FromArgb行不通。 - dou
@dou 你正在进行不必要的计算。GetPixel()在if条件中返回了White,你从条件本身就知道了这一点。因此,你不需要从Color.White中减去Color.White,你可以将其替换为Color.Black。 - Sergey Glotov
@dou 这会起作用吗?mPlan.SetPixel(x, y, new Color(white - mPlan.getPixel(x, y)) - Sergey Glotov
它可以工作,谢谢。 Plan.SetPixel(x, y, new Color(white - mPlan.getPixel(x, y)) - dou
1
我真的很想知道,if部分应该做什么。如果颜色是白色,并且你从白色中减去白色,你会得到黑色。或者不是吗? :) - Mars
我不知道 :) @dou应该知道他为什么需要它。 - Sergey Glotov

1

在Xamarin C#中,将int颜色转换为RGB颜色只需要执行以下操作:

Color myColor = new Color(yourBitmap.GetPixel(x,y);

然后,您可以像这样使用它的组件:
 byte myColorRedValue = myColor.R;
 byte myColorBlueValue = myColor.B;
 byte myColorGreenValue = myColor.G;
 byte myColorAlphaValue = myColor.A;

所以举个例子,如果你想让颜色变暗,只需这样做:
 myColor.R = (byte)(myColor.R / 2);
 myColor.G = (byte)(myColor.G / 2);
 myColor.B = (byte)(myColor.B / 2);

这将为您提供三个介于0和255之间的整数。要使颜色变暗,您只需用某个数字减去它们(显然,您必须检查结果是否大于或等于零)。
从初学者的角度来看,这是实现您想要的最简单的方法,并理解其工作原理。

我也尝试过,但我无法将Color.red用作方法。 - dou
OP使用的是C#,不是Java。 - Sergey Glotov
@Mars Color.Red 是代表红色的常量。我猜测它将会是 myColor.RmyColor.GmyColor.B - Sergey Glotov
非常抱歉,我忘记了C#,因为它不在标题中。我目前正在使用Xamarin Android进行工作,我会在几分钟内给您答复。 - yan yankelevich
@Mars 傻瓜我现在明白了 :) 是int类型,它们不会应用。 - Sergey Glotov
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接