我的游戏中有这样一个 fragment ,其中圆圈绘制不同的颜色,我希望玩家每次点击时都能看到 Toast
上显示的颜色名称,我怎样才能实现这一点?我的代码如下。任何帮助将不胜感激?我想以字符串形式显示它们,例如。如果 RGB 为红色,则显示字符串的红色信息。
static int x,y,r=255,g=255,b=255;
final static int radius=180;
Paint paint;
public Circle(Context context)
{
super(context);
paint=new Paint();
paint.setAntiAlias(true);
paint.setARGB(255, r, g, b);
setFocusable(true);
this.setOnTouchListener(this);
}
public void onDraw(Canvas canvas)
{
paint.setARGB(255, r, g, b);
canvas.drawCircle(x,y,radius,paint);
}
最佳答案
如果您希望将颜色名称与 RGB 值严格匹配,则需要将随机 RGB 与您选择的已知颜色进行匹配。例如,您可以使用 ColorUtils 类执行类似的操作:
class ColorUtils{
public static final Map<String, int[]> COLOR_MAP;
static{
COLOR_MAP = new HashMap<>();
COLOR_MAP.put("red", new int[]{255,0,0});
COLOR_MAP.put("blue", new int[]{0, 0, 255});
COLOR_MAP.put("green", new int[]{0, 255,0});
...
... //add more colors here
}
public static double findDist(int[] rgb, int[] color){
int deltaR = color[0] - rgb[0];
int deltaG = color[1] - rgb[1];
int deltaB = color[2] - rgb[2];
return (Math.pow(deltaR, 2) + Math.pow(deltaG, 2) + Math.pow(deltaB, 2));
}
public static String findClosestColor(int[] rgb, Map<String, int[]> colorMap){
int min = Integer.MAX_VALUE;
String color = null;
double dist;
for(Entry<String, int[]> entry : colorMap.entrySet()){
dist = findDist(rgb, entry.getValue());
if(dist < min){
dist = min;
color = entry.getKey();
}
}
return color;
}
}
像这样测试:
int[] teal = {2, 132, 130};
System.out.print(findClosestColor(teal, colorMap));
供您在 Android 中测试:
public boolean onTouch(View view,MotionEvent event){
x=(int)event.getX()-(radius/2);
y=(int)event.getY()-(radius/2);
randColor();
invalidate();
Toast.makeText(getContext(),
ColorUtils.findClosestColor(new int[]{r, g, b}, ColorUtils.COLOR_MAP), Toast.LENGTH_LONG).show();
return true;
}
为了您的利益,将这两个方法添加到实用程序类中,并静态创建颜色图,您将在其中填充您希望向用户表达的颜色。没有已知的库(据我所知!)能够将 RGB 映射到可以在 Java 中轻松访问的颜色。我可能是错的,但我也认为这是你最好的方法。
注意:最好将 Toast.makeText() 调用作为另一个方法存储在单独的 utils 类中(如果我使用 Toasts,我会这样做),这样可以稍微清理一下代码
class AndroidUtils{
public static void createToast(Context context, String str){
Toast.makeText(context, str, Toast.LENGTH_LONG).show();
}
}
然后只需调用它来代替上面的 toast:
AndroidUtils.createToast(getContext(), ColorUtils.findClosestColor(new int[]{r, g, b}, ColorUtils.COLOR_MAP));
关于java - 尝试在每次点击时显示颜色名称检查我的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32465372/