这是我写的代码:---
public class board extends Activity
{
Canvas canvas;Bitmap bitmap;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
DisplayMetrics metrics = getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
Log.d("board", "height is" + height + "width"+ width );
bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
Paint blue = new Paint();
Paint red = new Paint();
Paint green = new Paint();
Paint yellow = new Paint();
blue.setColor(Color.BLUE);
blue.setStrokeWidth(5);
red.setColor(Color.RED);
red.setStrokeWidth(5);
green.setColor(Color.GREEN);
green.setStrokeWidth(5);
yellow.setColor(Color.YELLOW);
yellow.setStrokeWidth(5);
canvas = new Canvas(bitmap);
canvas.drawColor(Color.BLACK);
red.setStyle(Paint.Style.FILL);
Path path = new Path();
path.setFillType(FillType.EVEN_ODD);
path.moveTo(width/5, height/3);
path.lineTo((4*width)/5, (height)/3);
path.moveTo((4*width)/5, (height)/3);
path.lineTo(width/2, (17*height)/30);
path.moveTo(width/2, (17*height)/30);
path.lineTo(width/5, height/3);
path.moveTo(width/5, height/3);
path.close();
canvas.drawPath(path, red);
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(bitmap);
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams params = new
RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
layout.addView(imageView, params);
layout.setBackgroundColor(Color.BLACK);
setContentView(layout);
}
所需产出: - 黑色背景上的红色填充三角形。
我得到的输出: - 只是一个黑色的背景。
导致错误的代码有什么问题。
答案 0 :(得分:6)
您只需要第一个 path.moveTo()。删除所有其他出现的path.moveTo():
Path path = new Path();
path.setFillType(FillType.EVEN_ODD);
path.moveTo(width/5, height/3); //<----- keep only this call to moveTo()
path.lineTo((4*width)/5, (height)/3);
path.moveTo((4*width)/5, (height)/3); //<----- remove this call
path.lineTo(width/2, (17*height)/30);
path.moveTo(width/2, (17*height)/30); //<----- remove this call
path.lineTo(width/5, height/3);
path.moveTo(width/5, height/3); //<----- remove this call
path.close();
canvas.drawPath(path, red);
//rest of the code