Android进阶篇-自定义图片伸缩控件具体实例

ZoomImageView.java:

代码如下:

/**
 * @author gongchaobin
 *
 *  自定义可伸缩的ImageView
 */
public class ZoomImageView extends View{
    /** 画笔类  **/
    private Paint mPaint;

private Runnable mRefresh = null;
    /** 缩放手势监听类  **/
    private ScaleGestureDetector mScaleDetector;
    /** 手势识别类  **/
    private GestureDetector mGestureDetector;
    /** 当前被渲染的Bitmap **/
    private Bitmap mBitmap;

private int mThisWidth = -1, mThisHeight = -1;

private Runnable mOnLayoutRunnable = null;

private Matrix mBaseMatrix = new Matrix();
    private Matrix mDisplayMatrix = new Matrix();
    private Matrix mSuppMatrix = new Matrix();
    private Matrix mMatrix = new Matrix();

/** 最大的拉伸比例   **/
    private float mMaxZoom;

private float[] mMatrixValues = new float[9];
    private Runnable mFling = null;

private double mLastDraw = 0;
    static final int sPaintDelay = 250;

public ZoomImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
        init();
    }

public ZoomImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        init();
    }

public ZoomImageView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        init();
    }

private void init() {
        mPaint = new Paint();
        // 图像抖动处理
        mPaint.setDither(true);
        // 过滤优化操作  加快显示
        mPaint.setFilterBitmap(true);
        // 去掉锯齿
        mPaint.setAntiAlias(true);

/** 刷新线程  **/
        mRefresh = new Runnable() {
            @Override
            public void run() {
                postInvalidate();
            }
        };

mScaleDetector = new ScaleGestureDetector(getContext(),new ScaleListener());
        mGestureDetector = new GestureDetector(getContext(),new MyGestureListener());

// 判断是否是新的API  开启硬件加速
        if(Build.VERSION.SDK_INT >=  Build.VERSION_CODES.HONEYCOMB) {
            setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }
    }

public Bitmap getImageBitmap() {
        return mBitmap;
    }

/** 回收Bitmap **/
    public void clear() {
        if(mBitmap != null && !mBitmap.isRecycled()) {
            mBitmap.recycle();
            mBitmap = null;
        }
    }

@Override
    protected void onLayout(boolean changed, int left, int top, int right,
            int bottom) {
        // TODO Auto-generated method stub
        super.onLayout(changed, left, top, right, bottom);

mThisWidth = right - left;
        mThisHeight = bottom - top;

Runnable r = mOnLayoutRunnable;
        if (r != null) {
            mOnLayoutRunnable = null;
            r.run();
        }

if (mBitmap != null) {
            setBaseMatrix(mBitmap, mBaseMatrix);
            setImageMatrix(getImageViewMatrix());
        }
    }

private void setBaseMatrix(Bitmap bitmap, Matrix matrix) {
        float viewWidth = getWidth();
        float viewHeight = getHeight();

matrix.reset();
        float widthScale = Math.min(viewWidth / (float)bitmap.getWidth(), 1.0f);
        float heightScale = Math.min(viewHeight / (float)bitmap.getHeight(), 1.0f);
        float scale;
        if (widthScale > heightScale) {
            scale = heightScale;
        } else {
            scale = widthScale;
        }

/** 算取比例  进行平移   **/
        matrix.setScale(scale, scale);
        matrix.postTranslate(
                (viewWidth  - ((float)bitmap.getWidth()  * scale))/2F,
                (viewHeight - ((float)bitmap.getHeight() * scale))/2F);
    }

protected Matrix getImageViewMatrix() {
        mDisplayMatrix.set(mBaseMatrix);
        mDisplayMatrix.postConcat(mSuppMatrix);
        return mDisplayMatrix;
    }

public void setImageMatrix(Matrix m){
        /** Matrix是否为空并是否定义   **/
        if (m != null && m.isIdentity()) {
            m = null;
        }

if (m == null && !this.mMatrix.isIdentity() || m != null && !this.mMatrix.equals(m)) {
            this.mMatrix.set(m);
            invalidate();
        }
    }

static private void translatePoint(Matrix matrix, float [] xy) {
        matrix.mapPoints(xy);
    }

/**
     * 设置Bitmap
     *
     * @param bitmap
     */
    public void setImageBitmap(final Bitmap bitmap) {
        final int viewWidth = getWidth();

// 开启硬件加速
        if( Build.VERSION.SDK_INT >=  Build.VERSION_CODES.HONEYCOMB && bitmap!=null && bitmap.getHeight()>1800 )
            setLayerType(View.LAYER_TYPE_SOFTWARE, null);

if (viewWidth <= 0)  {
            mOnLayoutRunnable = new Runnable() {
                public void run() {
                    setImageBitmap(bitmap);
                }
            };
            return;
        }

if (bitmap != null) {
            setBaseMatrix(bitmap, mBaseMatrix);
            this.mBitmap = bitmap;
        } else {
            mBaseMatrix.reset();
            this.mBitmap = bitmap;
        }

mSuppMatrix.reset();
        setImageMatrix(getImageViewMatrix());
        mMaxZoom = maxZoom();
        zoomTo(zoomDefault());
    }

public void zoomTo(float scale) {
        float width = getWidth();
        float height = getHeight();

zoomTo(scale, width/2F, height/2F);
    }

protected void zoomTo(float scale, float centerX, float centerY) {
        if (scale > mMaxZoom) {
            scale = mMaxZoom;
        }

float oldScale = getScale();
        float deltaScale = scale / oldScale;

/** 根据某个中心点按照比例缩放  **/
        mSuppMatrix.postScale(deltaScale, deltaScale, centerX, centerY);
        setImageMatrix(getImageViewMatrix());
        center(true, true, false);
    }

/**
     * 计算中心位置
     *
     * @param vertical
     * @param horizontal
     * @param animate
     */
    protected void center(boolean vertical, boolean horizontal, boolean animate) {
        if (mBitmap == null)
            return;

Matrix m = getImageViewMatrix();

float [] topLeft  = new float[] { 0, 0 };
        float [] botRight = new float[] { mBitmap.getWidth(), mBitmap.getHeight() };

translatePoint(m, topLeft);
        translatePoint(m, botRight);

float height = botRight[1] - topLeft[1];
        float width  = botRight[0] - topLeft[0];

float deltaX = 0, deltaY = 0;

if (vertical) {
            int viewHeight = getHeight();
            if (height < viewHeight) {
                deltaY = (viewHeight - height)/2 - topLeft[1];
            } else if (topLeft[1] > 0) {
                deltaY = -topLeft[1];
            } else if (botRight[1] < viewHeight) {
                deltaY = getHeight() - botRight[1];
            }
        }

if (horizontal) {
            int viewWidth = getWidth();
            if (width < viewWidth) {
                deltaX = (viewWidth - width)/2 - topLeft[0];
            } else if (topLeft[0] > 0) {
                deltaX = -topLeft[0];
            } else if (botRight[0] < viewWidth) {
                deltaX = viewWidth - botRight[0];
            }
        }

postTranslate(deltaX, deltaY);
        if (animate) {
            Animation a = new TranslateAnimation(-deltaX, 0, -deltaY, 0);
            a.setStartTime(SystemClock.elapsedRealtime());
            a.setDuration(250);
            setAnimation(a);
        }
        setImageMatrix(getImageViewMatrix());
    }

protected void postTranslate(float dx, float dy) {
        mSuppMatrix.postTranslate(dx, dy);
    }

public float getScale() {
        return getScale(mSuppMatrix);
    }

protected float getScale(Matrix matrix) {
        if(mBitmap!=null)
            return getValue(matrix, Matrix.MSCALE_X);
        else
            return 1f;
    }

protected float getValue(Matrix matrix, int whichValue) {
        matrix.getValues(mMatrixValues);
        return mMatrixValues[whichValue];
    }

/**
     * 计算最大的拉伸比例
     *
     * @return
     */
    protected float maxZoom() {
        if (mBitmap == null)
            return 1F;

float fw = (float) mBitmap.getWidth()  / (float)mThisWidth;
        float fh = (float) mBitmap.getHeight() / (float)mThisHeight;
        float max = Math.max(fw, fh) * 16;
        return max;
    }

/**
     * 原始显示比例
     *
     * @return
     */
    public float zoomDefault() {
        if (mBitmap == null)
            return 1F;

float fw = (float)mThisWidth/(float)mBitmap.getWidth();
        float fh = (float)mThisHeight/(float)mBitmap.getHeight();
        return Math.max(Math.min(fw, fh),1);
    }

protected void zoomTo(final float scale, final float centerX, final float centerY, final float durationMs) {
        final float incrementPerMs = (scale - getScale()) / durationMs;
        final float oldScale = getScale();
        final long startTime = System.currentTimeMillis();

post(new Runnable() {
            public void run() {
                long now = System.currentTimeMillis();
                float currentMs = Math.min(durationMs, (float)(now - startTime));
                float target = oldScale + (incrementPerMs * currentMs);
                zoomTo(target, centerX, centerY);

if (currentMs < durationMs) {
                    post(this);
                }
            }
        });
    }

protected void scrollBy( float distanceX, float distanceY, final float durationMs ){
        final float dx = distanceX;
        final float dy = distanceY;
        final long startTime = System.currentTimeMillis();

mFling = new Runnable() {
            float old_x    = 0;
            float old_y    = 0;

public void run()
            {
                long now = System.currentTimeMillis();
                float currentMs = Math.min( durationMs, now - startTime );
                float x = easeOut( currentMs, 0, dx, durationMs );
                float y = easeOut( currentMs, 0, dy, durationMs );
                postTranslate( ( x - old_x ), ( y - old_y ) );
                center(true, true, false);

old_x = x;
                old_y = y;
                if ( currentMs < durationMs ) {
                    post( this );
                }
            }
        };
        post( mFling );
    }

private float easeOut( float time, float start, float end, float duration){
        return end * ( ( time = time / duration - 1 ) * time * time + 1 ) + start;
    }

@Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        if(mBitmap!=null && !mBitmap.isRecycled() ){
            if( Build.VERSION.SDK_INT >=  Build.VERSION_CODES.HONEYCOMB && getLayerType() == View.LAYER_TYPE_HARDWARE ){
                canvas.drawBitmap(mBitmap, mMatrix, null);
            }else{
                if( (System.currentTimeMillis()-mLastDraw) > sPaintDelay ){
                    canvas.drawBitmap(mBitmap, mMatrix, mPaint);
                    mLastDraw = System.currentTimeMillis();
                }
                else{
                    canvas.drawBitmap(mBitmap, mMatrix, null);
                    removeCallbacks(mRefresh);
                    postDelayed(mRefresh, sPaintDelay);
                }
            }
        }
    }

/**
     * @author Administrator
     *
     * 手势缩放监听
     */
    class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

@Override
        public boolean onScale(ScaleGestureDetector detector) {
            // TODO Auto-generated method stub
            Log.i("ZoomImageView", "onScale");
            if(detector!=null && detector.isInProgress()){
                try{
                    float targetScale = getScale() * detector.getScaleFactor();
                    targetScale = Math.min(maxZoom(), Math.max(targetScale, 1.0f) );

zoomTo(targetScale, detector.getFocusX(), detector.getFocusY() );
                    invalidate();
                    return true;
                }catch(IllegalArgumentException e){
                    e.printStackTrace();
                }
            }
            return false;
        }
    };

/**
     * @author Administrator
     *
     * 手势识别监听
     */
    class MyGestureListener extends GestureDetector.SimpleOnGestureListener {

@Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                float distanceX, float distanceY) {
            // TODO Auto-generated method stub
            Log.i("ZoomImageView", "onScroll");
            if((e1 != null && e1.getPointerCount() > 1) || (e2 != null && e2.getPointerCount() > 1)
                    || (mScaleDetector != null && mScaleDetector.isInProgress())){
                return false;
            }

if(getScale() > zoomDefault() ) {
                removeCallbacks(mFling);
                postTranslate(-distanceX, -distanceY);
                center(true, true, false);
            }

return true;
        }

@Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY) {
            Log.i("ZoomImageView", "onFling");
            // TODO Auto-generated method stub
            if ((e1!=null && e1.getPointerCount() > 1) || ( e2!=null && e2.getPointerCount() > 1))
                return false;
            if (mScaleDetector.isInProgress())
                return false;

try{
                float diffX = e2.getX() - e1.getX();
                float diffY = e2.getY() - e1.getY();

if ( Math.abs( velocityX ) > 800 || Math.abs( velocityY ) > 800 ) {
                    scrollBy( diffX / 2, diffY / 2, 300 );
                    invalidate();
                }
            }catch(NullPointerException  e){
                e.printStackTrace();
            }

return super.onFling( e1, e2, velocityX, velocityY );
        }

@Override
        public boolean onDoubleTap(MotionEvent e) {
            // TODO Auto-generated method stub
            Log.i("ZoomImageView", "onDoubleTap");
            if ( getScale() > zoomDefault() ){
                zoomTo(zoomDefault());
            }
            else
                zoomTo(zoomDefault()*3, e.getX(), e.getY(),200);
            return true;
        }

@Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            // TODO Auto-generated method stub
            Log.i("ZoomImageView", "onSingleTapConfirmed");
            // 设置点击事件
            if(mImageTouchedListener != null) {
                mImageTouchedListener.onImageTouched();
                return false;
            }
            return super.onSingleTapConfirmed(e);
        }

}

@Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        if(mBitmap != null) {
            mScaleDetector.onTouchEvent(event);

if(!mScaleDetector.isInProgress()) {
                mGestureDetector.onTouchEvent(event);
            }
        }

return true;
    };

/**
     *
     * @author Administrator
     *
     * 点击接口
     */
    private onImageTouchedListener mImageTouchedListener;

public interface onImageTouchedListener {
        void onImageTouched();
    }

public void setOnImageTouchedListener(onImageTouchedListener listener ){
        this.mImageTouchedListener = listener;
    }

xml布局:

代码如下:

<com.example.pay.ZoomImageView
        android:scaleType="matrix"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/zommImageView"
        />

activity调用方法:

代码如下:

mZoomImageView = (ZoomImageView) findViewById(R.id.zommImageView);
        mZoomImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
        mZoomImageView.setOnImageTouchedListener(new onImageTouchedListener() {

@Override
            public void onImageTouched() {
                // TODO Auto-generated method stub
                Toast.makeText(MainActivity.this, "11111", Toast.LENGTH_LONG).show();
            }
        });

(0)

相关推荐

  • Android实现自定义轮播图片控件示例

    要完成一个轮播图片,首先想到的应该是使用ViewPager来实现.ViewPager已经有了滑动的功能,我们只要让它自己滚动.再加上下方的小圆点就行了.所以我们本次的自定义控件就是由ViewPager和LinearLayout叠加起来组成的. 直接先上效果图: 创建一个自定义的ViewPager 先上完整的代码 package com.kcode.autoscrollviewpager.view; import android.content.Context; import android.os

  • Android中利用matrix 控制图片的旋转、缩放、移动

    本文主要讲解利用android中Matrix控制图形的旋转缩放移动,具体参见一下代码: 复制代码 代码如下: /**  * 使用矩阵控制图片移动.缩放.旋转  */  public class CommonImgEffectView extends View { private Context context ;      private Bitmap mainBmp , controlBmp ;      private int mainBmpWidth , mainBmpHeight , c

  • Android自定义View实现多图片选择控件

    前言 相信很多朋友在开发中都会遇到图片上传的情况,尤其是多图上传,最经典的莫过于微信的图片选择了.所有很多情况下会使用到多图选择,所以就有了这篇文章,今天抽点时间写了个控件.  •支持自定义选择图片的样式  •支持设置图片选择数量  •支持图片预览,删除  •支持图片拍照 先来看看效果 实现分析 假如不定义控件,我们要实现这样一个功能,无非是写个GridView在item点击的时候去显示图片进行选择,在返回界面的时候进行GridView的数据刷新.我们把这些逻辑写在我们自定义的GridView中

  • Android使用控件ImageView加载图片的方法

    在 Android 加载图片一般使用 ImageView,这里简单记录一下这个控件的使用方法. 最简单就是在 xml 里直接使用 ImageView 标签: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="

  • Android 图片网格布局控件示例代码

    项目地址:MultiPictureView MultiPictureView是一个可以将多张图片以网格的方式显示的View,通过简单的接口实现烦人的布局,从此解放你的小手手 显示效果 支持设置图片数量上限 支持设置最多显示列数 支持动态布局和静态布局两种模式(见下图) 支持编辑模式和展示模式(编辑模式可以增加和删除图片) 布局方式 动态布局 静态布局 编辑/显示模式 如何使用 1. 在布局中声明 <com.goyourfly.multi_picture.MultiPictureView andr

  • Android控件ImageSwitcher实现左右图片切换功能

    ImageSwitcher类是ViewSwitcher类的子类,它实现的效果是在完成ImageView的切换并且带有动画效果.要使用这个类需要以下两个步骤: 1)为ImageSwitcher类提供一个ViewFactory,该ViewFactory生成的View组件必须是ImageView. 2)需要切换的时候,只需要嗲用ImageSwitcher的setImageDrawable().setImageResource().setImageURL()方法即可实现切换. activity_main

  • Android中让图片自适应控件的大小的方法

    这就需要把.png格式的图片转成.9.png格式,.9.png就是后缀名.在安装Android-SDK时自带了<draw9patch.bat>可以把.png格式的图片编辑后保存就变成了.9.png格式.这个文件存放在你所安装的Android-SDK目录->sdk->tools目录下. .9.png格式在Andriod中可以做到根据控件大小自适应,最重要的是不会失真.是不是很完美?下面就来看是如何制作.9.png格式的进度条. 启动后的界面如下: 首先要准备要转换的png图片,并把图

  • android 多点触摸图片缩放的具体实现方法

    布局: 复制代码 代码如下: <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/relativeLayout1"    android:layout_width="fill_parent

  • Android编程实现GridView控件点击图片变暗效果的方法

    本文实例讲述了Android编程实现GridView控件点击图片变暗效果的方法.分享给大家供大家参考,具体如下: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); grid = (GridView) findViewById(R.id.grid); grid.setAdapte

  • Android中ImageView.src设置图片拉伸、填满控件的方法

    问题 ImageView.src设置图片资源,图片不拉伸了,却有空隙部分: <LinearLayout android:id="@+id/linearLayout1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <ImageView andro

  • Android实现自定义轮播图片控件详解

    首先上效果图 实现原理 要完成一个轮播图片,首先想到的应该是使用ViewPager来实现.ViewPager已经有了滑动的功能,我们只要让它自己滚动.再加上下方的小圆点就行了.所以我们本次的自定义控件就是由ViewPager和LinearLayout叠加起来组成的. 一.创建一个自定义的ViewPager 先上完整的代码 package com.kcode.autoscrollviewpager.view; import android.content.Context; import andro

  • Android编程实现图片放大缩小功能ZoomControls控件用法实例

    本文实例讲述了Android编程实现图片放大缩小功能ZoomControls控件用法.分享给大家供大家参考,具体如下: MainActivity代码: package example.com.myapplication; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import

随机推荐