看看这本书 -《Android游戏编程之从零开始》
Day_3 2019/01/21
Bitmap 位图的渲染与操作
首先,最简单的如何生成一张位图,如下
Bitmap bitmap = BitmapFactory.decodeResource( this.getResources() , R.mipmap.ic_launcher );
下面是常用的操作函数
public class BitmapSurfaceView extends SurfaceView implements SurfaceHolder.Callback
{
private SurfaceHolder holder;
private Canvas canvas;
private Bitmap bitmap = BitmapFactory.decodeResource( this.getResources() , R.mipmap.ic_launcher );
private Paint paint;
public BitmapSurfaceView( Context context )
{
super( context );
holder = this.getHolder();
holder.addCallback( this );
setFocusable( true );
paint = new Paint();
paint.setColor( Color.BLACK );
}
@Override
public void surfaceCreated( SurfaceHolder surfaceHolder )
{
myDraw();
}
private void myDraw()
{
try
{
canvas = holder.lockCanvas();
if( canvas != null )
{
//用于保存当前画布的状态
canvas.save();
//旋转方式1
canvas.rotate( 30 , bitmap.getWidth() / 2 , bitmap.getHeight() / 2 );
canvas.drawBitmap( bitmap , 0 , 0 , paint );
//用于恢复上次保存的画布状态
canvas.restore();
canvas.drawBitmap( bitmap , 100 , 0 , paint );
//旋转方式2
Matrix mx = new Matrix();
mx.postRotate( 30 , bitmap.getWidth() / 2 , bitmap.getHeight() / 2 );
canvas.drawBitmap( bitmap , mx , paint );
//平移位图方式1
canvas.save();
//平移距离可小于0,表示往左移动
canvas.translate( 10 , 10 );
canvas.drawBitmap( bitmap , 0 , 0 , paint );
canvas.restore();
//平移位图方式2
Matrix matrix = new Matrix();
matrix.postTranslate( 10 , 10 );
canvas.drawBitmap( bitmap , matrix , paint );
//缩放位图
canvas.save();
//============x轴缩放比例===y轴的===========x轴起始点==========================y轴起始点
canvas.scale( 2f , 2f , 50 + bitmap.getWidth() / 2 , 50 + bitmap.getHeight() / 2 );
canvas.drawBitmap( bitmap , 50 , 50 , paint );
canvas.restore();
canvas.drawBitmap( bitmap , 50 , 50 , paint );
//x轴镜像
canvas.save();
canvas.scale( -1 , 1 , bitmap.getWidth() / 2 , bitmap.getHeight() / 2 );
canvas.drawBitmap( bitmap , 0 , 0 , paint );
canvas.restore();
//y轴镜像
canvas.save();
canvas.scale( 1 , -1 , bitmap.getWidth() / 2 , bitmap.getHeight() / 2 );
canvas.drawBitmap( bitmap , 0 , 0 , paint );
canvas.restore();
//x轴镜像
canvas.drawBitmap( bitmap , 0 , 0 , paint );
Matrix matrix1 = new Matrix();
//使用矩阵的移动方法
matrix.postTranslate( 100 , 100 );
matrix.postScale( -1 , 1 , 100 + bitmap.getWidth() / 2 , 100 + bitmap.getHeight() / 2 );
canvas.drawBitmap( bitmap , matrix1 , paint );
//y轴镜像
canvas.drawBitmap( bitmap , 0 , 0 , paint );
Matrix matrix2 = new Matrix();
//使用矩阵的移动方法
matrix2.postTranslate( 100 , 100 );
matrix2.postScale( 1 , -1 , 100 + bitmap.getWidth() / 2 , 100 + bitmap.getHeight() / 2 );
canvas.drawBitmap( bitmap , matrix2 , paint );
}
}
catch( Exception e )
{
e.printStackTrace();
}
finally
{
if( canvas != null )
{
holder.unlockCanvasAndPost( canvas );
}
}
}
@Override
public void surfaceChanged(
SurfaceHolder surfaceHolder ,
int i ,
int i1 ,
int i2 )
{
}
@Override
public void surfaceDestroyed( SurfaceHolder surfaceHolder )
{
}
}