安卓中drawBitmap绘制图像方法

来源:互联网 发布:centos websocket 编辑:程序博客网 时间:2024/05/21 09:34

drawBitmap方法:绘制图像

【功能说明】该方法用于在画布上绘制图像,通过指定Bitmap对象来实现。前面的各个方法都是自己绘制各个图形,但我们的应用程序往往需要直接引用一些图片资源。这个时候,便可以使用drawBitmap方法来在画布上直接显示图像。

【基本语法】public void drawBitmap (Bitmap bitmap, float left, float top, Paint paint)

参数说明

bitmap:Bitmap对象,代表了图像资源。

left:图像显示的左边位置。

top:图像显示的上边位置。

paint:绘制时所使用的画笔。

【实例演示】下面通过代码来演示如何在画布上绘制图像。

  1. protected void onDraw(Canvas canvas) {  
  2.     // TODO Auto-generated method stub  
  3.     super.onDraw(canvas);  
  4.     paint.setAntiAlias(true);                       //设置画笔为无锯齿  
  5.     paint.setColor(Color.BLACK);                    //设置画笔颜色  
  6.     canvas.drawColor(Color.WHITE);                  //白色背景  
  7.     paint.setStrokeWidth((float) 3.0);              //线宽  
  8.     paint.setStyle(Style.STROKE);  
  9.       
  10.     Bitmap bitmap=null;                         //Bitmap对象  
  11.     bitmap=((BitmapDrawable)getResources().getDrawable(R.drawable.icon)).getBitmap();  
  12.     canvas.drawBitmap(bitmap, 50, 50, null);        //绘制图像  
  13.     bitmap=((BitmapDrawable)getResources().getDrawable(R.drawable.bulb_on)).getBitmap();  
  14.     canvas.drawBitmap(bitmap, 50, 150, null);       //绘制图像  
  15.     bitmap=((BitmapDrawable)getResources().getDrawable(R.drawable.bulb_off)).getBitmap();  
  16.     canvas.drawBitmap(bitmap, 50, 450, null);       //绘制图像  
  17. }  

在这段代码中,首先初始化画笔和画布,然后声明了一个Bitmap对象。接着,从资源文件中获取图片资源,并使用drawBitmap方法将图片显示在画布上。
0 0