Android Path 使用

 

Android Path 使用


項目中經常會用到繪圖方面的知識,之前一直對Path這個類的使用不是很清楚,現在系統的使用和總結一下。首先看一下API中的解釋:

The Path class encapsulates compound (multiple contour) geometric paths consisting of straight line segments, quadratic curves, and cubic curves. It can be drawn with canvas.drawPath(path, paint), either filled or stroked (based on the paint's Style), or it can be used for clipping or to draw text on a path.

爲程序添加水印的效果,就是通過onDraw()然後根據Path畫出來的

[java] view plaincopy
  1. public class WaterMark extends Activity{  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         // TODO Auto-generated method stub  
  6.         super.onCreate(savedInstanceState);  
  7.         setContentView(new WaterMarkView(this));  
  8.     }  
  9.       
  10.     private class WaterMarkView extends View{  
  11.         private Bitmap mBitmap;  
  12.         private Context mContext;  
  13.         private Paint mPaint;  
  14.         private static final String WATER_MARK_STRING= "HYF_AN_E V2.6.3 Demo";  
  15.   
  16.         public WaterMarkView(Context context) {  
  17.             super(context);  
  18.             mContext = context;  
  19.             mPaint = new Paint();  
  20.             mPaint.setAntiAlias(true);  
  21.             mBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.my_image);  
  22.         }  
  23.           
  24.         @Override  
  25.         protected void onDraw(Canvas canvas) {  
  26.             // TODO Auto-generated method stub  
  27.             super.onDraw(canvas);  
  28.               
  29.             canvas.drawBitmap(mBitmap, 00, mPaint);  
  30.             drawWaterMark(canvas,getWidth(),getHeight());  
  31.         }  
  32.   
  33.         private void drawWaterMark(Canvas canvas, int width, int height) {  
  34.             int fontSize = 35;  
  35.             Path path = new Path();  
  36.             path.moveTo(0, height);  
  37.             path.lineTo(width, 0);  
  38.             path.close();  
  39.               
  40.             Paint paint = new Paint();  
  41.             paint.setColor(0x88ff0000);  
  42.             paint.setTextSize(fontSize);  
  43.             paint.setAntiAlias(true);  
  44.             paint.setDither(true);  
  45.             Rect bounds = new Rect();  
  46.             paint.getTextBounds(WATER_MARK_STRING, 0, WATER_MARK_STRING.length(), bounds);  
  47.               
  48.             int length = (int)Math.sqrt(width*width + height*height);  
  49.             int hOffset = (length - (bounds.right - bounds.left)) / 2;  
  50.             canvas.drawTextOnPath(WATER_MARK_STRING, path, hOffset, fontSize/2, paint);  
  51.         }  
  52.     }  
  53. }  

後一種效果是先畫水印然後畫圖片,所以畫的時候是有順序的:

[java] view plaincopy
  1. drawWaterMark(canvas,getWidth(),getHeight());  
  2. canvas.drawBitmap(mBitmap, 00, mPaint);  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章