【问题标题】:Color cannot be converted to int颜色无法转换为 int
【发布时间】:2014-11-21 17:35:40
【问题描述】:

我遇到了一个奇怪的错误,我无法使用 Color 对象设置绘画对象的颜色,这很奇怪,因为 paint.setColor(Color.RED) 有效而 paint.setColor(this.color) 无效

这是我的代码。

public class Shape{
    protected GameView2 game_view;
    protected int x;
    protected int y;
    protected int width;
    protected int height;
    protected Color color;

    public Shape(GameView2 game_view, Color color, int x, int y, int width, int height) {
        this.game_view = game_view;
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.color = color;
    }

    public void onDraw(Canvas canvas){

        Paint paint = new Paint();
        Rect rec = new Rect(x, y, x + width, y + height);
        paint.setColor(this.color); //does not work
        paint.setStyle(Paint.Style.FILL);
        canvas.drawRect(rec, paint);        
    }
}

编辑:

Shape 对象已被声明为另一个名为 GameView 的类, 它非常大,所以我不会粘贴整个类,但是当创建一个 Shape 对象时,这是完成的:

new Shape(this, Color.BLACK, 0, 0, 100, 100)

我得到的错误是incompatible types: Color cannot be converted to int

【问题讨论】:

  • 你得到什么样的错误?能否请您添加 Paint 类的代码?
  • 阅读文档。特别是 Color.BLACKColor.RED 的文档

标签: java android colors


【解决方案1】:

setColor 需要 int 类型但 this.color 不是 int,您尝试设置颜色对象而不是 int 值。

public native void setColor(int color);

【讨论】:

  • 好的,谢谢,我已将Color color 更改为int color
【解决方案2】:

查看documentation,您会看到Color 是一个提供静态方法来处理颜色整数的实用程序类。您实际上可以实例化 Color 对象似乎是一个历史错误。

【讨论】:

  • 是的。我不明白为什么颜色不是抽象的。实例化一个没有多大意义。
【解决方案3】:

您如何将Color 传递给您的新Shape

你应该使用

getResources().getColor(R.color.idcolor);

在 xml 中:

<color name="idcolor">#123456</color>

编辑

根据您的编辑,尝试将颜色声明为int。颜色实际上是int,主要颜色在Color中声明为静态字段

protected int color;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    相关资源
    最近更新 更多