postScale:设置图片的缩放
package com.example.examples_05_09;
import android.R.integer;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;
@SuppressLint("DrawAllocation")
public class GameView extends View implements Runnable {
Bitmap QQBit;//位图
int QQBitWidth=0;//宽度
int QQBitHeight=0;//高度
//实例化图像对象
Matrix matrix=new Matrix();
float sc=1.0f;//设置缩放
public GameView(Context context) {
super(context);
// TODO Auto-generated constructor stub
//获取图片
QQBit=((BitmapDrawable)getResources().getDrawable(R.drawable.qq)).getBitmap();
//获取高
QQBitHeight=QQBit.getHeight();
//获取宽
QQBitWidth=QQBit.getWidth();
new Thread(this).start();
}
public void run() {
// TODO Auto-generated method stub
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(100);
} catch (Exception e) {
// TODO: handle exception
Thread.currentThread().interrupt();
}
postInvalidate();
}
}
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
matrix.reset();
//设置缩放大小
matrix.postScale(sc, sc);
//重新获得设置好的位图
Bitmap bitmap=Bitmap.createBitmap(QQBit, 0, 0, QQBitWidth, QQBitHeight,matrix,true);
//绘制
GameView.drawImage(canvas, bitmap, (320-QQBitWidth)/2, 20);
}
//绘制
public static void drawImage(Canvas canvas,Bitmap bitmap,int x,int y) {
canvas.drawBitmap(bitmap, x, y, null);
}
}
package com.example.examples_05_09;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.Menu;
public class MainActivity extends Activity {
GameView gameView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameView=new GameView(this);
setContentView(gameView);
}
public boolean onKeyDown(int keyCode,KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_DPAD_LEFT)
if(gameView.sc>0.3)
{
gameView.sc-=0.1;
}
else if (keyCode==KeyEvent.KEYCODE_DPAD_RIGHT) {
if(gameView.sc<1.5)
{
gameView.sc+=0.1;
}
}
return true;
}
}
图像缩小和扩大
时间: 2024-11-05 23:38:19