項目中經常會用到繪圖方面的知識,之前一直對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畫出來的
- public class WaterMark extends Activity{
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(new WaterMarkView(this));
- }
- private class WaterMarkView extends View{
- private Bitmap mBitmap;
- private Context mContext;
- private Paint mPaint;
- private static final String WATER_MARK_STRING= "HYF_AN_E V2.6.3 Demo";
- public WaterMarkView(Context context) {
- super(context);
- mContext = context;
- mPaint = new Paint();
- mPaint.setAntiAlias(true);
- mBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.my_image);
- }
- @Override
- protected void onDraw(Canvas canvas) {
- // TODO Auto-generated method stub
- super.onDraw(canvas);
- canvas.drawBitmap(mBitmap, 0, 0, mPaint);
- drawWaterMark(canvas,getWidth(),getHeight());
- }
- private void drawWaterMark(Canvas canvas, int width, int height) {
- int fontSize = 35;
- Path path = new Path();
- path.moveTo(0, height);
- path.lineTo(width, 0);
- path.close();
- Paint paint = new Paint();
- paint.setColor(0x88ff0000);
- paint.setTextSize(fontSize);
- paint.setAntiAlias(true);
- paint.setDither(true);
- Rect bounds = new Rect();
- paint.getTextBounds(WATER_MARK_STRING, 0, WATER_MARK_STRING.length(), bounds);
- int length = (int)Math.sqrt(width*width + height*height);
- int hOffset = (length - (bounds.right - bounds.left)) / 2;
- canvas.drawTextOnPath(WATER_MARK_STRING, path, hOffset, fontSize/2, paint);
- }
- }
- }
後一種效果是先畫水印然後畫圖片,所以畫的時候是有順序的:
- drawWaterMark(canvas,getWidth(),getHeight());
- canvas.drawBitmap(mBitmap, 0, 0, mPaint);