`

Canvas ,Paint,Bitmap画图

 
阅读更多
Canvas画布,所有画出来的图形都在Canvas上,Paint是画笔,用来渲染画布上画出来的图形,而Bitmap是一个图片的容器,用来存放图片的。
paint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));  
        paint.setColor(Color.BLUE);  
        canvas.drawText("自定义View,canvas对象已经存在。", 30, 40, paint);  
        canvas.drawRect(10, 10, 30, 30, paint); 

如上,设置好了Paint的样式后,在canvas上画文本或者矩形都可以。
如果要画一张图片出来,就要像下面这样了。
Bitmap iconbit = BitmapFactory.decodeResource(getResources(), R.drawable.icon) ;  
        canvas.drawBitmap(iconbit, 40,40, paint);  

下面是把一个bitmap变成drawable
  
   Bitmap bitmap = Bitmap.createBitmap(200, 100, Config.ARGB_8888) ;   
  
  ImageView imgView  = new ImageView(this) ; 
   //将Bitmap对象转换为Drawable图像资  
   Drawable drawable = new BitmapDrawable(bitmap) ;  
  imgView .setBackgroundDrawable(drawable) ; 


下面这段代码,在bitmap上既画了iconbit又画了一个矩形。
Paint paint = new Paint();
    	Bitmap iconbit = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher) ;  
    	paint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
		paint.setColor(Color.RED);
		
		Bitmap bitmap = Bitmap.createBitmap(200, 300, Config.ARGB_8888); 
		Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(iconbit, 0,0, paint);  
        
        Rect rect = new Rect (10,80,180,120) ;  
        
        //当前的画图区域为Rect裁剪的区域,而不是我们之前赋值的bitmap  
        canvas.clipRect(rect)  ;  
        canvas.drawColor(Color.YELLOW);  
        paint.setColor(Color.BLACK);  
        canvas.drawText("裁剪clip后画图区域-黄色部分", 10,100,paint) ;  
        change.setImageBitmap(bitmap);


下面是使用save和restore方法的示例:
Paint paint = new Paint();
    	 //将icon图像转换为Bitmap对象  
        Bitmap iconbit = BitmapFactory.decodeResource(getResources(), R.drawable.ic_action_search) ;  
          
        //创建一个的Bitmap对象  
        Bitmap bitmap = Bitmap.createBitmap(400, 400, Config.ARGB_8888)  ;  
     
        Canvas canvas = new Canvas (bitmap) ;  
  
        paint.setColor(Color.GREEN);  
        paint.setTextSize(30);  //设置字体大小  
        canvas.drawText("我没有旋转",30, 40, paint);  

        canvas.save() ;  
          
        canvas.rotate(30) ;  
        paint.setTextSize(13);
        paint.setColor(Color.BLACK);
        canvas.drawText("我是旋转的",115,20, paint);  
          
        canvas.restore();  
        
        paint.setColor(Color.BLUE);
        canvas.drawText("我没有旋转",115,20, paint);  
  
        //将Bitmap对象转换为Drawable图像资  
        //为ImageView设置图像  
        change.setImageBitmap(bitmap);  
          
//        Drawable drawable = new BitmapDrawable(bitmap) ;  
//        change.setBackgroundDrawable(drawable) ; 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics