自定义视图不会绘制位图

时间:2015-10-24 12:47:16

标签: android bitmap

我试图在蓝天上显示移动的云。显示蓝色背景但不显示云。我在这里尝试了其他问题的不同方法,但没有任何作用。我的代码是:

public class CloudBackground extends View {

Bitmap cloud;
int x = 0;
int y = 0;
Paint paint = new Paint();
Rect rectangle = new Rect(0,0,100,100);

public CloudBackground(Context context,AttributeSet attrs) {
    super(context,attrs);
    cloud = BitmapFactory.decodeResource(getResources(),R.drawable.cloud1);
}

@Override
protected void onDraw (Canvas canvas){
    super.onDraw(canvas);

    Rect back = new Rect();
    back.set(0,0,canvas.getWidth(), canvas.getHeight());

    Paint pBlue = new Paint();
    pBlue.setStyle(Paint.Style.FILL);
    pBlue.setColor(Color.CYAN);

    canvas.drawRect(back, pBlue);

    drawCloud(x,y,canvas);

    if (x < canvas.getWidth())
        x = x + 10;
    else { 
        y = y + 10;
        x = 0;
    }
    invalidate();

}

private void drawCloud(int x2, int y2, Canvas canvas) {
    canvas.drawBitmap(cloud, x2, y2,paint);

}

2 个答案:

答案 0 :(得分:0)

确定。试试这个:

public CloudBackground(Context context,AttributeSet attrs) {
    super(context,attrs);
    cloud = BitmapFactory.decodeResource(context.getApplicationContext().getResources(),R.drawable.cloud1);
}

答案 1 :(得分:0)

最终使用a.jpg而不是.png解决了这个问题。就这么简单,没有理由。