如何更改在画布上创建的圆圈的颜色,详细信息:在画布上创建的圆圈是我的代码
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
private static class SampleView extends View {
// CONSTRUCTOR
public SampleView(Context context) {
super(context);
setFocusable(true);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.CYAN);
Paint p = new Paint();
// smooths
p.setAntiAlias(true);
p.setColor(Color.RED);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(4.5f);
// opacity
//p.setAlpha(0x80); //
canvas.drawCircle(50, 50, 30, p);
}
}
}
此处将此画布附加到imageview。现在如何在每个水龙头上改变这个圆圈的颜色,意味着第一次点击我想要红色,第二次点击需要绿色,第三次点击回到正常状态。怎么做。
答案 0 :(得分:1)
您可以通过以下方式实现:
- >有一个静态变量(static int DESIRED_COLOR;
),可用于存储您想要的颜色代码
- >而不是修复,p.setColor(Color.RED);
使用一些静态变量,如:p.setColor(DESIRED_COLOR);
- >在每次触摸时,根据您的要求更改该静态变量(DESIRED_COLOR
)的值,例如:DESIRED_COLOR = Color.GREEN
答案 1 :(得分:1)
请参阅下面的解决方案。
public class MainActivity extends Activity implements OnTouchListener{
SampleView mSampleView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSampleView = new SampleView(this);
setContentView(mSampleView);
mSampleView.setOnTouchListener(this);
}
private static class SampleView extends View{
public static int i = 0;
Paint p;
// CONSTRUCTOR
public SampleView(Context context) {
super(context);
setFocusable(true);
p = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
Log.i("i = ", "1");
canvas.drawColor(Color.CYAN);
p.setAntiAlias(true);
if(i==0)
p.setColor(Color.RED);
else if (i==1)
p.setColor(Color.BLUE);
else
p.setColor(Color.GREEN);
p.setStyle(Paint.Style.FILL_AND_STROKE);
p.setStrokeWidth(4.5f);
canvas.drawCircle(500, 500, 100, p);
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
mSampleView.i=(mSampleView.i+1)%3;
v.invalidate();
return false;
}
}