限制比例以适应屏幕上的图像缩放

时间:2012-10-30 12:23:56

标签: android zoom limit scale

我目前正在开发一个应用程序,我需要一个可以放大的图像视图。我找到了正确的代码,但缩放或拖出时的图像不会停留在图像边框。我将不胜感激,谢谢。

public class test extends Activity implements OnTouchListener {
private static final String TAG = "Touch";
@SuppressWarnings("unused")
private static final float MIN_ZOOM = 1f, MAX_ZOOM = 1f;

// These matrices will be used to scale points of the image
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();

// The 3 states (events) which the user is trying to perform
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;

// these PointF objects are used to record the point(s) the user is touching
PointF start = new PointF();
PointF mid = new PointF();
int picx;
int picy;
float oldDist = 1f;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ImageView view = (ImageView) findViewById(R.id.imageView1);
    view.setOnTouchListener(this);
}

public boolean onTouch(View v, MotionEvent event) {
    ImageView view = (ImageView) v;

    view.setScaleType(ImageView.ScaleType.MATRIX);
    float scale;

    dumpEvent(event);
    // Handle touch events here...

    switch (event.getAction() & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN: // first finger down only
        savedMatrix.set(matrix);
        start.set(event.getX(), event.getY());
        Log.d(TAG, "mode=DRAG"); // write to LogCat
        mode = DRAG;
        break;

    case MotionEvent.ACTION_UP: // first finger lifted

    case MotionEvent.ACTION_POINTER_UP: // second finger lifted

        mode = NONE;
        Log.d(TAG, "mode=NONE");
        break;

    case MotionEvent.ACTION_POINTER_DOWN: // first and second finger down

        oldDist = spacing(event);
        Log.d(TAG, "oldDist=" + oldDist);
        if (oldDist > 5f) {
            savedMatrix.set(matrix);
            midPoint(mid, event);
            mode = ZOOM;
            Log.d(TAG, "mode=ZOOM");
        }
        break;

    case MotionEvent.ACTION_MOVE:

        if (mode == DRAG) {

            matrix.set(savedMatrix);
            matrix.postTranslate(event.getX() - start.x, event.getY()
                    - start.y); // create the transformation in the matrix
                                // of points
        } else if (mode == ZOOM) {
            // pinch zooming
            float newDist = spacing(event);
            Log.d(TAG, "newDist=" + newDist);
            if (newDist > 5f) {
                matrix.set(savedMatrix);
                scale = newDist / oldDist; // setting the scaling of the
                                            // matrix...if scale > 1 means
                                            // zoom in...if scale < 1 means
                                            // zoom out
                matrix.postScale(scale, scale, mid.x, mid.y);
            }
        }
        break;
    }

    view.setImageMatrix(matrix); // display the transformation on screen

    return true; // indicate event was handled
}

/*
 * --------------------------------------------------------------------------
 * Method: spacing Parameters: MotionEvent Returns: float Description:
 * checks the spacing between the two fingers on touch
 * ----------------------------------------------------
 */

private float spacing(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);
}

/*
 * --------------------------------------------------------------------------
 * Method: midPoint Parameters: PointF object, MotionEvent Returns: void
 * Description: calculates the midpoint between the two fingers
 * ------------------------------------------------------------
 */

private void midPoint(PointF point, MotionEvent event) {
    float x = event.getX(0) + event.getX(1);
    float y = event.getY(0) + event.getY(1);
    point.set(x / 2, y / 2);
}

/** Show an event in the LogCat view, for debugging */
private void dumpEvent(MotionEvent event) {
    String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
            "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
    StringBuilder sb = new StringBuilder();
    int action = event.getAction();
    int actionCode = action & MotionEvent.ACTION_MASK;
    sb.append("event ACTION_").append(names[actionCode]);

    if (actionCode == MotionEvent.ACTION_POINTER_DOWN
            || actionCode == MotionEvent.ACTION_POINTER_UP) {
        sb.append("(pid ").append(
                action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
        sb.append(")");
    }

    sb.append("[");
    for (int i = 0; i < event.getPointerCount(); i++) {
        sb.append("#").append(i);
        sb.append("(pid ").append(event.getPointerId(i));
        sb.append(")=").append((int) event.getX(i));
        sb.append(",").append((int) event.getY(i));
        if (i + 1 < event.getPointerCount())
            sb.append(";");
    }

    sb.append("]");
    Log.d("Touch Events ---------", sb.toString());
}

}

1 个答案:

答案 0 :(得分:0)

很难对矩阵这么做,所以我用一些数学解决方案编写了一些代码来实现这一点。

使用此视图的zoomIn(),zoomOut,setBitmapResource()。

public class ZoomView extends View {

public static interface ZoomViewClickListner{
    void onZoomViewClick(View v);


}

public ZoomView(Context context) {
    super(context);
}
private ZoomViewClickListner zoomViewClickListener;
private int viewHeight;

private int viewWidth;
private float ratio;
private float zoomFactor = 2f;

private Bitmap image;
private Rect drawingRect;

private int offsetX = 0, offsetY = 0;
private int drawingHeight;
private int drawingWidth;

private boolean scrollableHorizontal = false;
private boolean scrollableVertical = false;


public ZoomView(Context context, AttributeSet attrs) {
    super(context, attrs);
}
public void setZoomViewClickListener(ZoomViewClickListner zoomViewClickListener) {
    this.zoomViewClickListener = zoomViewClickListener;
}
@Override
protected void onDraw(Canvas canvas) {
    viewHeight = getHeight();
    viewWidth = getWidth();

    drawingHeight = (int) (viewHeight * zoomFactor);
    drawingWidth = (int) (ratio * viewHeight * zoomFactor);

    //      System.out.println("height:::"+viewHeight+"   width:::"+viewWidth);
    drawingRect = new Rect((viewWidth-drawingWidth)/2 + offsetX, (viewHeight - drawingHeight)/2 + offsetY, (drawingWidth+(viewWidth-drawingWidth)/2) + offsetX,(viewHeight - drawingHeight)/2+drawingHeight + offsetY);
    if(image != null)
        canvas.drawBitmap(image, null, drawingRect, null);

    if(viewHeight < drawingHeight) scrollableVertical = true;
    else scrollableVertical = false;

    if(viewWidth < drawingWidth) scrollableHorizontal = true;
    else scrollableHorizontal = false;

    super.onDraw(canvas);
}

float touchX, touchY , initOffsetX, initOffsetY ;

@Override
public boolean onTouchEvent(MotionEvent event) {

    switch(event.getAction()){

    case MotionEvent.ACTION_DOWN:

        touchX = event.getX();
        touchY = event.getY();
        initOffsetX = offsetX;
        initOffsetY = offsetY;
        break;
    case MotionEvent.ACTION_MOVE:
        if(scrollableVertical){
            offsetY = (int) (initOffsetY + event.getY() - touchY);
        }
        if(scrollableHorizontal){
            offsetX = (int) (initOffsetX + event.getX() - touchX);
        }

        break;
    case MotionEvent.ACTION_UP:

        if((Math.abs((event.getY() - touchY)) < 10) && ((event.getX() - touchX) < 10)){
            System.out.println("Action up");
            if (zoomViewClickListener != null) {
                zoomViewClickListener.onZoomViewClick(this);
            }

        }

        break;
    }

    validateOffsets();
    return true;
}

private void validateOffsets(){
    if (scrollableVertical) {
        if (((viewHeight - drawingHeight) / 2 + offsetY) > 0) {
            offsetY = (drawingHeight - viewHeight) / 2;
        }
        if ((viewHeight - drawingHeight) > ((viewHeight - drawingHeight) / 2 + offsetY)) {
            offsetY = (viewHeight - drawingHeight) / 2;
        }
    }
    if (scrollableHorizontal) {
        if (((viewWidth - drawingWidth) / 2 + offsetX) > 0) {
            offsetX = (drawingWidth - viewWidth) / 2;
        }
        if ((viewWidth - drawingWidth) > ((viewWidth - drawingWidth) / 2 + offsetX)) {
            offsetX = (viewWidth - drawingWidth) / 2;
        }
    }
    invalidate();
}

public void zoomIn(){
    System.out.println("Zooming In");
    if(zoomFactor < 3)
        zoomFactor += 0.1;
    validateOffsets();
}
public void zoomOut(){
    System.out.println("Zooming Out");
    if(zoomFactor > 1)
        zoomFactor -= 0.1;
    validateOffsets();
}

public void setBitmapResource(int id){
    image = ((BitmapDrawable)getContext().getResources().getDrawable(id)).getBitmap();
    //      imgRect = new Rect(0, 0, image.getWidth(), image.getHeight());
    ratio = (float)image.getWidth()/image.getHeight();

    zoomFactor = 1.0f;
    offsetX = 0; 
    offsetY = 0;
    invalidate();
}

}