Setting background image in a custom view

2019-08-07 06:01发布

问题:

I have created a class which extends View class.

public class SplashScreen extends View

and i use it by setting contentview

View splash = new SplashScreen(this);
setContentView(splash);

I need to set background image but I can't use layout. I think I need to do canvas drawing but I don't know how to do.

protected void onDraw(Canvas canvas) {
  ballBounds.set(ballX-ballRadius, ballY-ballRadius, ballX+ballRadius, ballY+ballRadius);
  paint.setColor(Color.LTGRAY);
  // canvas.drawImage(R.drawable.background_image); (Ps: I know there is no function such as drawImage)"
  canvas.drawOval(ballBounds, paint);}

回答1:

If you want to just set the background you can do

public SplashScreen(Context context, AttributeSet attrs) {
    super(context, attrs);
    setBackgroundResource(R.drawable.background);
}


回答2:

you can add image on canvas as:

        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pic180);  
        Matrix matrix=new Matrix();
        matrix.postScale(0.8f, 0.8f);
        matrix.postRotate(45);
        Bitmap dstbmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),
        bmp.getHeight(),matrix,true);
        canvas.drawColor(Color.BLACK); 
        canvas.drawBitmap(dstbmp, 10, 10, null); 


回答3:

Don't you just want to change SplachScreen type to activity? Then setContentView change to whatever your layout is and if you want that splach screen appear before your application, make it first in Manifest and in splashscreen end, destroy activity and start your application menu activity. Then you won't need View class and less work finding where is problem