Android 图片实现单击放大缩小

Android 图片实现单击放大缩小

记录使用

 <ImageView
       android:id="@+id/iv"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_gravity="center"
       android:src="@drawable/opencar"/>
 public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private ImageView iv;
    private static final String TAG = "MainActivity";
    public boolean isAmplification=false;
    /**
     * false 没放大  默认就是原始大小
     *true  放大了
     * */
    public Matrix matrix=new Matrix();
    public Bitmap bitmap;
    public float scaleWidth;
    public float scaleHeight;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DisplayMetrics dm=new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int height=dm.heightPixels;
        int width=dm.widthPixels;
        /*获取 屏幕的 高和宽 */
        initView();
        bitmap=((BitmapDrawable)iv.getDrawable()).getBitmap();//取imageview里面src 资源
        scaleWidth=width/bitmap.getWidth();//求倍率
        scaleHeight=height/bitmap.getHeight();
    }


    private void initView() {
        iv = (ImageView) findViewById(R.id.iv);
        iv.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId())
        {
            case R.id.iv:
                if(!isAmplification)
                {
                    /* 放大*/
                    matrix.set(iv.getImageMatrix());
                    matrix.postScale(scaleWidth,scaleHeight);
                    Bitmap newbitmap=Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
                    iv.setImageBitmap(newbitmap);
                    isAmplification=true;
                }
                else {
                    /*缩小*/
                    matrix.set(iv.getImageMatrix());
                    matrix.postScale(1.0f,1.0f);
                    Bitmap newbitmap=Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
                    iv.setImageBitmap(newbitmap);
                    isAmplification=false;
                }
                break;


            default:break;

        }
    }
}

你可能感兴趣的:(Android学习)