canvas.scale(scale,scale,x,y)

时间:2013-06-05 08:30:51

标签: android canvas view

我需要缩放图像。但问题是,如果我使用偏离x来缩放时间,则y指向图像向左或向右跳跃。

我需要在x,y - >点进行缩放。 canvas.scale(scale,scale,x,y);不是在0,0点 - > canvas.scale(scale,scale);

public class Img extends View {
private Paint paint;

private Rect imgRect; 
private Bitmap img;

private int h, w;
private int x, y;
private float scale = 1f;

private int scaleX, scaleY;
private int aScaleX, aScaleY;

public img(Context context) {
    super(context);

    paint = new Paint();

    img = BitmapFactory.decodeResource(getResources(), R.drawable.uebersicht);
    w = 1330;
    h = 846;     
    imgRect = new Rect(0, 0, w, h);     
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);               

    canvas.scale(scale, scale, scaleX, scaleY);

    paint.setColor(Color.WHITE); 
    canvas.drawBitmap(img, null, imgRect, paint);       

    canvas.restore();

    paint.setColor(Color.RED);
    paint.setTextSize(30);
    canvas.drawText(String.valueOf(scale), 10, 25, paint);
}   

public void reDrawPos(int rX, int rY) {
    x -= rX;
    y -= rY;

    calcImg();      
    invalidate();       
}

public void reDrawScale(float s) {
    scale = s;  

    calcImg();      
    invalidate();
}

private void calcImg() {
    mapRect.set(x, y, x+w, y+h);
}

public float scaleSet(int sX, int sY) { 
    scaleX = sX;
    scaleY = sY;

    return scale;
}}

任何人都可以帮助我吗?

Thanx for Help Bobert

1 个答案:

答案 0 :(得分:1)

有一个方便的方法叫做Matrix.setRectToRect(RectF,RectF,ScaleToFit)来帮助你。

Matrix imageMatrix = imageView.getImageMatrix();
RectF drawableRect = new RectF(0, 0, imageWidth, imageHeight);
RectF viewRect = new RectF(0, 0, imageView.getWidth(), imageView.getHeight());
imageMatrix.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.CENTER);
imageView.setImageMatrix(m);

这应该将矩阵imageMatrix设置为具有缩放组合并转换所需的值,以显示drawable居中并适合ImageView小部件。

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.save();
    canvas.setMatrix(imageMatrix);
    ((BitmapDrawable)mIcon).draw(canvas);
    canvas.restore();
}