Bobert
Bobert

Reputation: 276

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

i need to scale a image. But the problem is that if i scale secunde time with diverent x,y point the image jump left or right.

I need to scale at point x,y -> canvas.scale(scale, scale, x, y); not at point 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;
}}

Can any one help me?

Thanx for Help Bobert

Upvotes: 0

Views: 884

Answers (1)

blganesh101
blganesh101

Reputation: 3695

There's a convenient method called Matrix.setRectToRect(RectF, RectF, ScaleToFit) to help you here.

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);

That should set the matrix imageMatrix to have combo of scaling and translate values that is needed to show the drawable centered and fit within the ImageView widget.

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

Upvotes: 1

Related Questions