我正在创建一个绘画应用程序。
在我的程序中有一个名为tool的变量存储正在使用的工具的名称。最初它设置为空闲但当工具更改为任何其他工具时,当我将工具切换回空闲时,然后用黑色清除屏幕
。结果我无法伸出手,但只有一个点出现在我的手指之后。
我调试了程序,发现一旦调用清除黑色屏幕的语句,即使它没有被定义为调用它也会被调用。这是我的代码片段:
if(tool.equals("freeHand")){
Log.d("free","move");
try{
canvas=null;
canvas = holder.lockCanvas();
synchronized (holder) {
//draw(canvas);
canvas2.drawBitmap(backup,0,0,paint);
canvas2.drawLine(startX, startY, moveX ,moveY, paint);
//backup=Bitmap.createBitmap(cache);
draw(canvas);
}
}finally{
if(canvas != null){
holder.unlockCanvasAndPost(canvas);
// backup=Bitmap.createBitmap(cache);
}
}
//canvas2.drawLine(startX, startY, moveX ,moveY, paint);
startX = moveX;
startY = moveY;
//backup=Bitmap.createBitmap(cache);
}
else{
if(!tool.equals("freeHand") ){
canvas2.drawColor(Color.BLACK);
Log.d("free", "bug");
}
if(tool=="line"){
try{
canvas=null;
canvas = holder.lockCanvas();
synchronized (holder) {
//draw(canvas);
canvas2.drawBitmap(backup,0,0,paint);
canvas2.drawLine(downX,downY,moveX,moveY, paint);
draw(canvas);
}
}finally{
if(canvas != null){
holder.unlockCanvasAndPost(canvas);
}
}
//canvas2.drawBitmap(backup, 0, 0, paint);
//canvas2.drawLine(downX,downY,moveX,moveY, paint);
}
if(tool == "strokeRect"){
try{
canvas=null;
canvas = holder.lockCanvas();
synchronized (holder) {
//draw(canvas);
canvas2.drawBitmap(backup,0,0,paint);
canvas2.drawCircle(moveX, moveY, 20, paint);
draw(canvas);
}
}finally{
if(canvas != null){
holder.unlockCanvasAndPost(canvas);
}
}
//canvas2.drawCircle(moveX, moveY, 20, paint);
}
if(tool == "fillRect"){
try{
canvas=null;
canvas = holder.lockCanvas();
synchronized (holder) {
//draw(canvas);
canvas2.drawBitmap(backup,0,0,paint);
canvas2.drawRect(downX, downY, moveX, moveY, paint);
draw(canvas);
}
}finally{
if(canvas != null){
holder.unlockCanvasAndPost(canvas);
}
}
//canvas2.drawRect(downX, downY, moveX, moveY, paint);
}
if(tool=="img"){
try{
canvas=null;
canvas = holder.lockCanvas();
synchronized (holder) {
//draw(canvas);
canvas2.drawBitmap(backup,0,0,paint);
canvas2.drawBitmap(img,moveX,moveY,paint);
//canvas2.drawBitmap(backup,0,0,paint);
draw(canvas);
}
}finally{
if(canvas != null){
holder.unlockCanvasAndPost(canvas);
}
}
}
}
我认为声明:
canvas2.drawColor(Color.BLACK);
造成了这个问题。
如何摆脱不必要的声明调用?
答案 0 :(得分:1)
您无法比较这样的字符串:
tool!="freeHand"
如果两个对象不是同一个对象,则字符串是对象和!=
测试。
相反,使用equals()
方法测试字符串的内容:
!tool.equals("freeHand")
由于“字符串实习”,有时!=
和==
会起作用,但您不应该依赖它。
http://en.wikipedia.org/wiki/String_interning
您可能还考虑不使用字符串。枚举怎么样?
public enum Tool {Freehand, Eraser, Paintbrush }
...
private Tool tool;
...
tool = Tool.Freehand;
...
if(tool == Tool.Freehand)
{
...
}
好多了......
答案 1 :(得分:0)
当您使用黑色清除屏幕时,它将清除屏幕上的所有内容,现在即使您将颜色设置为原始颜色,您之前绘制的任何内容都将不可见,它将被颜色透支。 / p>
当我将工具切换回空闲时,屏幕会被清除 黑色的
当您切换回来时,您必须再次设置颜色,否则一旦设置它将保持原样