我有一个扩展视图的类。下面是构造函数。在构造函数中,我将值分配给private int r,g,b;
。分配了正确的值。
public CanvasView(Context c, int r, int g, int b) {
super(c);
context = c;
this.r = r;
this.g = g;
this.b = b;
Log.i("RGB:", "r" + r + "g" + g + "b" + b); //logs correct values
}
在onDraw(请参阅下文)中,当我访问所有值时,它们均为零。
@Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
hsv = new float[3];
Color.RGBToHSV(r, g, b, hsv);
hsv[2] = getVal();
Log.i("RGBdraw:", "r" + r + "g" + g + "b" + b); //values are all 0
if (canvas != null){
canvas.drawColor(Color.rgb(r, g, b));
}
}
我以为在分配私有变量时,它们可以访问整个类吗?
非常感谢任何帮助。
编辑
这是最小的例子
在另一个类中,我创建视图
CanvasView mCanvasView = new CanvasView(mContext, 255, 0, 171);
下面是称为CanvasView的类,该类由上面的代码创建。我将3个整数传递给CanvasView。
public class CanvasView extends View {
private Context context;
private int r,g,b;
public CanvasView(Context c, int r, int g, int b) {
super(c);
context = c;
this.r = r;
this.g = g;
this.b = b;
Log.i("RGB:", "r" + r + "g" + g + "b" + b); //Correct values are logged
}
@Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
Log.i("RGB draw:", "r" + r + "g"+g + "b"+b); //Values here are all 0
if (canvas != null){
canvas.drawColor(Color.rgb(r, g, b));
}
}
}
最佳答案
而不是像在Java中那样创建类:CanvasView mCanvasView = new CanvasView(mContext, 255, 0, 171);
以android方式创建类:CanvasView mView = (CanvasView) findViewById(R.id.canvasView);
然后将吸气剂和吸气剂用于红色,绿色,蓝色
public void red(int r){
this.r = r;
}
public int getRed(){
return r;
}
像这样传递值:
mView.red(255);