NinePath的使用实例

SurfaceView类:
public class MySurfaceView extends SurfaceView implements Callback, Runnable {

	Thread thread;
	SurfaceHolder sfh;
	Paint paint;
	Canvas canvas;
	Bitmap bitmap_old;
	Bitmap bitmao_nine;
	NinePatch ninepath;
	public MySurfaceView(Context context) {
		super(context);
		sfh = this.getHolder();
		sfh.addCallback(this);
		paint = new Paint();
		paint.setColor(Color.BLUE);
		paint.setAntiAlias(true);
		thread = new Thread(this);
		bitmap_old = BitmapFactory.decodeResource(getResources(), R.drawable.frist );
		bitmao_nine = BitmapFactory.decodeResource(getResources(), R.drawable.second);
		
		//创建一个ninePatch的对象实例,第一个参数是bitmap、第二个参数是byte[],这里其实要求我们传入
		//如何处理拉伸方式,当然我们不需要自己传入,因为“.9.png”图片自身有这些信息数据,
		//也就是我们用“9path”工具操作的信息! 我们直接用“.9.png”图片自身的数据调用getNinePatchChunk()即可
		//第三个参数是图片源的名称,这个参数为可选参数,直接null~就OK~
		ninepath = new NinePatch(bitmao_nine, bitmao_nine.getNinePatchChunk(), null);
	}

	@Override
	public void run() {
		while(true){
			draw();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		thread.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		
	}
	
	private void draw(){
		try {
			canvas = sfh.lockCanvas();
			canvas.drawColor(Color.BLACK);
			//下面是对正常情况下的png图片的绘画方法
			RectF rect_old_two = new RectF(0, 150, bitmap_old.getWidth()*2, bitmap_old.getHeight()+200);
			canvas.drawBitmap(bitmap_old, 10, 10, paint);
			canvas.drawBitmap(bitmap_old, null, rect_old_two, paint);
			//下面是对png图片通过9Path工具生成的"*.9.png"图像的绘画方法
			RectF ninepath_two = new RectF(250, 150, bitmao_nine.getWidth()*2+250, bitmao_nine.getHeight()*2+90);
			canvas.drawBitmap(bitmao_nine, 270, 10, paint);
			ninepath.draw(canvas, ninepath_two);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(canvas != null){
				sfh.unlockCanvasAndPost(canvas);
			}
		}
		
	}

}


主类:
public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MySurfaceView(this));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

效果图:
NinePath的使用实例_第1张图片

你可能感兴趣的:(NinePath的使用实例)