上一篇文章介绍了怎么把图片保存到指定的文件夹目录下。今天就来说说如何实现图片的缩放。
很明显我们需要一个工具类:直接上代码吧!
DragImageView.java
package cn.guyu.util; import com.example.fragmenttabhost.R; import com.guyu.fragmenttabhost.HahItemActivity; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.os.AsyncTask; import android.text.method.MovementMethod; import android.util.AttributeSet; import android.util.FloatMath; import android.util.Log; import android.view.MotionEvent; import android.view.animation.AccelerateInterpolator; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.ScaleAnimation; import android.widget.ImageView; /**** * 这里你要明白几个方法执行的流程: 首先ImageView是继承自View的子类. * onLayout方法:是一个回调方法.该方法会在在View中的layout方法中执行,在执行layout方法前面会首先执行setFrame方法. * layout方法: * setFrame方法:判断我们的View是否发生变化,如果发生变化,那么将最新的l,t,r,b传递给View,然后刷新进行动态更新UI. * 并且返回ture.没有变化返回false. * * invalidate方法:用于刷新当前控件, * * */ public class DragImageView extends ImageView { private Activity mActivity; private int screen_W, screen_H;// 可见屏幕的宽高度 private int bitmap_W, bitmap_H;// 当前图片宽高 private int MAX_W, MAX_H, MIN_W, MIN_H;// 极限值 private int current_Top, current_Right, current_Bottom, current_Left;// 当前图片上下左右坐标 private int start_Top = -1, start_Right = -1, start_Bottom = -1, start_Left = -1;// 初始化默认位置. private int start_x, start_y, current_x, current_y;// 触摸位置 private float beforeLenght, afterLenght;// 两触点距离 private float scale_temp;// 缩放比例 /** * 模式 NONE:无 DRAG:拖拽. ZOOM:缩放 * * */ private enum MODE { NONE, DRAG, ZOOM }; private MODE mode = MODE.NONE;// 默认模式 private boolean isControl_V = false;// 垂直监控 private boolean isControl_H = false;// 水平监控 private ScaleAnimation scaleAnimation;// 缩放动画 private boolean isScaleAnim = false;// 缩放动画 private MyAsyncTask myAsyncTask;// 异步动画 /** 构造方法 **/ public DragImageView(Context context) { super(context); } public void setmActivity(Activity mActivity) { this.mActivity = mActivity; //findViewById(R.id.haha_back_bt); } /** 可见屏幕宽度 **/ public void setScreen_W(int screen_W) { this.screen_W = screen_W; } /** 可见屏幕高度 **/ public void setScreen_H(int screen_H) { this.screen_H = screen_H; } public DragImageView(Context context, AttributeSet attrs) { super(context, attrs); } /*** * 设置显示图片 */ @Override public void setImageBitmap(Bitmap bm) { super.setImageBitmap(bm); /** 获取图片宽高 **/ bitmap_W = bm.getWidth(); bitmap_H = bm.getHeight(); MAX_W = bitmap_W * 3; MAX_H = bitmap_H * 3; MIN_W = bitmap_W / 2; MIN_H = bitmap_H / 2; } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (start_Top == -1) { start_Top = top; start_Left = left; start_Bottom = bottom; start_Right = right; } } /*** * touch 事件 */ @Override public boolean onTouchEvent(MotionEvent event) { /** 处理单点、多点触摸 **/ switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: onTouchDown(event); break; // 多点触摸 case MotionEvent.ACTION_POINTER_DOWN: onPointerDown(event); break; case MotionEvent.ACTION_MOVE: onTouchMove(event); break; case MotionEvent.ACTION_UP: mode = MODE.NONE; break; // 多点松开 case MotionEvent.ACTION_POINTER_UP: mode = MODE.NONE; /** 执行缩放还原 **/ if (isScaleAnim) { doScaleAnim(); } break; } return true; } /** 按下 **/ void onTouchDown(MotionEvent event) { mode = MODE.DRAG; current_x = (int) event.getRawX(); current_y = (int) event.getRawY(); start_x = (int) event.getX(); start_y = current_y - this.getTop(); } /** 两个手指 只能放大缩小 **/ void onPointerDown(MotionEvent event) { if (event.getPointerCount() == 2) { mode = MODE.ZOOM; beforeLenght = getDistance(event);// 获取两点的距离 } } /** 移动的处理 **/ void onTouchMove(MotionEvent event) { int left = 0, top = 0, right = 0, bottom = 0; /** 处理拖动 **/ if (mode == MODE.DRAG) { /** 在这里要进行判断处理,防止在drag时候越界 **/ /** 获取相应的l,t,r ,b **/ left = current_x - start_x; right = current_x + this.getWidth() - start_x; top = current_y - start_y; bottom = current_y - start_y + this.getHeight(); /** 水平进行判断 **/ if (isControl_H) { if (left >= 0) { left = 0; right = this.getWidth(); } if (right <= screen_W) { left = screen_W - this.getWidth(); right = screen_W; } } else { left = this.getLeft(); right = this.getRight(); } /** 垂直判断 **/ if (isControl_V) { if (top >= 0) { top = 0; bottom = this.getHeight(); } if (bottom <= screen_H) { top = screen_H - this.getHeight(); bottom = screen_H; } } else { top = this.getTop(); bottom = this.getBottom(); } if (isControl_H || isControl_V) this.setPosition(left, top, right, bottom); current_x = (int) event.getRawX(); current_y = (int) event.getRawY(); } /** 处理缩放 **/ else if (mode == MODE.ZOOM) { afterLenght = getDistance(event);// 获取两点的距离 float gapLenght = afterLenght - beforeLenght;// 变化的长度 if (Math.abs(gapLenght) > 5f) { scale_temp = afterLenght / beforeLenght;// 求的缩放的比例 this.setScale(scale_temp); beforeLenght = afterLenght; } } } /** 获取两点的距离 **/ float getDistance(MotionEvent event) { float x = event.getX(0) - event.getX(1); float y = event.getY(0) - event.getY(1); return FloatMath.sqrt(x * x + y * y); } /** 实现处理拖动 **/ private void setPosition(int left, int top, int right, int bottom) { this.layout(left, top, right, bottom); } /** 处理缩放 **/ void setScale(float scale) { int disX = (int) (this.getWidth() * Math.abs(1 - scale)) / 4;// 获取缩放水平距离 int disY = (int) (this.getHeight() * Math.abs(1 - scale)) / 4;// 获取缩放垂直距离 // 放大 if (scale > 1 && this.getWidth() <= MAX_W) { current_Left = this.getLeft() - disX; current_Top = this.getTop() - disY; current_Right = this.getRight() + disX; current_Bottom = this.getBottom() + disY; this.setFrame(current_Left, current_Top, current_Right, current_Bottom); /*** * 此时因为考虑到对称,所以只做一遍判断就可以了。 */ if (current_Top <= 0 && current_Bottom >= screen_H) { // Log.e("jj", "屏幕高度=" + this.getHeight()); isControl_V = true;// 开启垂直监控 } else { isControl_V = false; } if (current_Left <= 0 && current_Right >= screen_W) { isControl_H = true;// 开启水平监控 } else { isControl_H = false; } } // 缩小 else if (scale < 1 && this.getWidth() >= MIN_W) { current_Left = this.getLeft() + disX; current_Top = this.getTop() + disY; current_Right = this.getRight() - disX; current_Bottom = this.getBottom() - disY; /*** * 在这里要进行缩放处理 */ // 上边越界 if (isControl_V && current_Top > 0) { current_Top = 0; current_Bottom = this.getBottom() - 2 * disY; if (current_Bottom < screen_H) { current_Bottom = screen_H; isControl_V = false;// 关闭垂直监听 } } // 下边越界 if (isControl_V && current_Bottom < screen_H) { current_Bottom = screen_H; current_Top = this.getTop() + 2 * disY; if (current_Top > 0) { current_Top = 0; isControl_V = false;// 关闭垂直监听 } } // 左边越界 if (isControl_H && current_Left >= 0) { current_Left = 0; current_Right = this.getRight() - 2 * disX; if (current_Right <= screen_W) { current_Right = screen_W; isControl_H = false;// 关闭 } } // 右边越界 if (isControl_H && current_Right <= screen_W) { current_Right = screen_W; current_Left = this.getLeft() + 2 * disX; if (current_Left >= 0) { current_Left = 0; isControl_H = false;// 关闭 } } if (isControl_H || isControl_V) { this.setFrame(current_Left, current_Top, current_Right, current_Bottom); } else { this.setFrame(current_Left, current_Top, current_Right, current_Bottom); isScaleAnim = true;// 开启缩放动画 } } } /*** * 缩放动画处理 */ public void doScaleAnim() { myAsyncTask = new MyAsyncTask(screen_W, this.getWidth(), this.getHeight()); myAsyncTask.setLTRB(this.getLeft(), this.getTop(), this.getRight(), this.getBottom()); myAsyncTask.execute(); isScaleAnim = false;// 关闭动画 } /*** * 回缩动画執行 */ class MyAsyncTask extends AsyncTask<Void, Integer, Void> { private int screen_W, current_Width, current_Height; private int left, top, right, bottom; private float scale_WH;// 宽高的比例 /** 当前的位置属性 **/ public void setLTRB(int left, int top, int right, int bottom) { this.left = left; this.top = top; this.right = right; this.bottom = bottom; } private float STEP = 8f;// 步伐 private float step_H, step_V;// 水平步伐,垂直步伐 public MyAsyncTask(int screen_W, int current_Width, int current_Height) { super(); this.screen_W = screen_W; this.current_Width = current_Width; this.current_Height = current_Height; scale_WH = (float) current_Height / current_Width; step_H = STEP; step_V = scale_WH * STEP; } @Override protected Void doInBackground(Void... params) { while (current_Width <= screen_W) { left -= step_H; top -= step_V; right += step_H; bottom += step_V; current_Width += 2 * step_H; left = Math.max(left, start_Left); top = Math.max(top, start_Top); right = Math.min(right, start_Right); bottom = Math.min(bottom, start_Bottom); Log.e("jj", "top="+top+",bottom="+bottom+",left="+left+",right="+right); onProgressUpdate(new Integer[] { left, top, right, bottom }); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } return null; } @Override protected void onProgressUpdate(final Integer... values) { super.onProgressUpdate(values); mActivity.runOnUiThread(new Runnable() { @Override public void run() { setFrame(values[0], values[1], values[2], values[3]); } }); } } }可直接拿来使用。然后在你的Activity中调用这个工具类。现在我把我工程里的Activity提出来!
HahItemActivity.java
package com.guyu.fragmenttabhost; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.view.ViewGroup.LayoutParams; import android.view.ViewTreeObserver; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.view.WindowManager; import android.widget.ImageView; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import cn.guyu.NetUtils.ImageLoader; import cn.guyu.util.DragImageView; import com.example.fragmenttabhost.R; public class HahItemActivity extends Activity { private int window_width, window_height;// 控件宽度 private ViewTreeObserver HviewTreeObserver; private DragImageView dImageView;// 自定义控件 private int state_height;// 状态栏的高度 final private int SUCCESS = 0; final private int ERROR = 1; TextView tv, tv_save, tv_fenx; private ImageView iv_hahaItem,backHahaImag,saveHahaImag; Bitmap btImage, btImageUI,btImag; private FileOutputStream out; private PopupWindow mPopupWindow; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == SUCCESS) { btImageUI = (Bitmap) msg.obj; btImag =getBitmap(btImageUI, window_width, window_height); dImageView.setImageBitmap(btImag); // dImageView.setmActivity(this); } else { // Toast.makeText(HahItemActivity.this, "加载失败", // Toast.LENGTH_SHORT).show(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.hah_item); /** 获取可見区域高度 **/ WindowManager manager = getWindowManager(); window_width = manager.getDefaultDisplay().getWidth(); window_height = manager.getDefaultDisplay().getHeight(); dImageView = (DragImageView) findViewById(R.id.iv_hahaItem); backHahaImag = (ImageView) findViewById(R.id.haha_back_bt); saveHahaImag = (ImageView) findViewById(R.id.haha_save_bt); //dImageView.setmActivity(this); final String urlImage = (String) getIntent().getStringExtra("ImageUrl"); new Thread(new Runnable() { @Override public void run() { try { // btImage = getBitmap(urlImage); btImage = ImageLoader.getImage(urlImage); } catch (IOException e) { e.printStackTrace(); } if (btImage != null) { Message msg = new Message(); msg.what = SUCCESS; msg.obj = btImage; handler.sendMessage(msg); } } }).start(); System.out.println("onclik_______________________________________________________"); backHahaImag.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { finish(); } }); saveHahaImag.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 保存图片到sd卡中 System.out.println(Environment.getExternalStorageDirectory() + "/Cool/" + "000000000000000000000000000"); // saveBitmapToSD(btImage); //mPopupWindow.dismiss(); // File file = new // File(Environment.getExternalStorageDirectory(), // System.currentTimeMillis()+".jpg"); if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED))// 判断是否可以对SDcard进行操作 { // 获取SDCard指定目录下 String sdCardDir = Environment .getExternalStorageDirectory() + "/CoolImage/"; File dirFile = new File(sdCardDir); if (!dirFile.exists()) { dirFile.mkdirs(); } File file = new File(sdCardDir, System.currentTimeMillis() + ".jpg");// 在SDcard的目录下创建图片文 try { out = new FileOutputStream(file); btImageUI.compress(Bitmap.CompressFormat.JPEG, 90, out); System.out .println("_____________sd__________________________"); } catch (FileNotFoundException e) { e.printStackTrace(); } try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } Toast.makeText( HahItemActivity.this, "已经保存至" + Environment.getExternalStorageDirectory() + "/CoolImage/" + "目录下", Toast.LENGTH_SHORT) .show(); } } }); dImageView.setmActivity(this); HviewTreeObserver = dImageView.getViewTreeObserver(); HviewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { public void onGlobalLayout() { if (state_height == 0) { // 获取状况栏高度 Rect frameH = new Rect(); getWindow().getDecorView() .getWindowVisibleDisplayFrame(frameH); state_height = frameH.top; dImageView.setScreen_H(window_height - state_height); dImageView.setScreen_W(window_width); } } }); /* 多触电事件,好像与这个有冲突 dImageView.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { finish(); // Toast.makeText(HahItemActivity.this,"你点我干嘛〉〉〉〉", // Toast.LENGTH_SHORT).show(); } }); dImageView.setOnLongClickListener(new OnLongClickListener() { public boolean onLongClick(View arg0) { // Toast.makeText(HahItemActivity.this,"你摸我干嘛", // Toast.LENGTH_SHORT).show(); showPopupWindow(); return false; } });*/ } public static Bitmap getBitmap(Bitmap bitmap, int screenWidth, int screenHight) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); Log.e("jj", "图片宽度" + w + ",screenWidth=" + screenWidth); Matrix matrix = new Matrix(); float scale = (float) screenWidth / w; float scale2 = (float) screenHight / h; // scale = scale < scale2 ? scale : scale2; // 保证图片不变形. matrix.postScale(scale, scale); // w,h是原图的属性. return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true); } /* 因为添加了图片缩放,避免造成触摸手势与点击事件的冲突,这里抛弃使用长按显示popupwindow,直接使用按钮Button. * public void showPopupWindow() { // Context mContext = HahItemActivity.this; LayoutInflater mLayoutInflater = (LayoutInflater) this .getSystemService(LAYOUT_INFLATER_SERVICE); // 保存转发等视图 View xuanz_popunwindwow = mLayoutInflater.inflate( R.layout.popwindow_image, null); // 转化为popunwindow mPopupWindow = new PopupWindow(xuanz_popunwindwow, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); mPopupWindow.setBackgroundDrawable(new BitmapDrawable()); mPopupWindow.setFocusable(true); mPopupWindow.setOutsideTouchable(true); mPopupWindow.update(); // 设置显示 mPopupWindow.showAtLocation(findViewById(R.id.hahaimage_pop_layout), Gravity.CENTER, 0, 0); tv_save = (TextView) xuanz_popunwindwow .findViewById(R.id.pop_save_image); // tv_save = (TextView)findViewById(R.id.pop_save_image); tv_save.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 保存图片到sd卡中 System.out.println(Environment.getExternalStorageDirectory() + "/Cool/" + "000000000000000000000000000"); // saveBitmapToSD(btImage); mPopupWindow.dismiss(); // File file = new // File(Environment.getExternalStorageDirectory(), // System.currentTimeMillis()+".jpg"); if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED))// 判断是否可以对SDcard进行操作 { // 获取SDCard指定目录下 String sdCardDir = Environment .getExternalStorageDirectory() + "/CoolImage/"; File dirFile = new File(sdCardDir); if (!dirFile.exists()) { dirFile.mkdirs(); } File file = new File(sdCardDir, System.currentTimeMillis() + ".jpg");// 在SDcard的目录下创建图片文 try { out = new FileOutputStream(file); btImage.compress(Bitmap.CompressFormat.JPEG, 90, out); System.out .println("_____________sd__________________________"); } catch (FileNotFoundException e) { e.printStackTrace(); } try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } Toast.makeText( HahItemActivity.this, "保存已经至" + Environment.getExternalStorageDirectory() + "/CoolImage/" + "目录下", Toast.LENGTH_SHORT) .show(); } } }); }*/ }hah_item.xml 采用真布局的格式
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/hahaimage_pop_layout"> <cn.guyu.util.DragImageView android:layout_gravity="center_vertical" android:id="@+id/iv_hahaItem" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/sbb" android:scaleType="fitXY" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="15dp" android:layout_gravity="top" android:background="@android:color/transparent" > <ImageView android:focusable="true" android:id="@+id/haha_back_bt" android:layout_gravity="center" android:layout_width="31dp" android:layout_height="20dp" android:layout_weight="1" android:src="@drawable/haha_back" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="5" /> <ImageView android:focusable="true" android:id="@+id/haha_save_bt" android:layout_gravity="center" android:layout_width="31dp" android:layout_height="20dp" android:layout_weight="1" android:src="@drawable/haha_save" /> </LinearLayout> </FrameLayout>