0

I am adding 1 layout dynamically. In that adding custom view. now I want to draw image on canvas exactly of same size as the size of that layout.

Below is the code of my custom view which i have tried.

public BlockView(Context context, Bitmap bitmap, int layoutHeight,
            int layoutWidth) {
        super(context);

        this.bitmap = bitmap;
        this.width = bitmap.getWidth();
        this.height = bitmap.getHeight();
        this.layoutHeight = layoutHeight;
        this.layoutWidth = layoutWidth;

        if (drawableWidth <= viewWidth && drawableHeight <= viewHeight) {
            scale = 1.0f;
        } else {
            scale = Math.min((float) viewWidth / (float) drawableWidth,
                    (float) viewHeight / (float) drawableHeight);
        }

        mDrawable = new BitmapDrawable(getResources(), bitmap);
    }

    private static float getDegreesFromRadians(float angle) {
        return (float) (angle * 180.0 / Math.PI);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        drawableWidth = mDrawable.getIntrinsicWidth();
        drawableHeight = mDrawable.getIntrinsicHeight();

        viewWidth = layoutWidth;
        viewHeight = layoutHeight;

        setMeasuredDimension(viewWidth, viewHeight);
    }

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

        int saveCount = canvas.save();

        matrix.setScale(scale, scale);
        matrix.postRotate(getDegreesFromRadians(angle));
        matrix.postTranslate(position.getX(), position.getY());

        canvas.concat(matrix);

        mDrawable.setBounds(0, 0, drawableWidth, drawableHeight);
        mDrawable.draw(canvas);

        canvas.restoreToCount(saveCount);
    }

With above code,I am successfully able to draw image and perform drag,zoom and rotate. But facing problem of not able to draw image of same size as the size of layout. and also need some way to proceed on how to check that image should not be scaled too small than the layout size.

Any help will be really appreciated.

Dig
  • 254
  • 1
  • 9
  • mDrawable.setBounds(0, 0, getWidth(), getHeight()); – ElDuderino Apr 24 '14 at 08:23
  • I tried it. but by using that, entire image is getting shrinked to fit area. By using `mDrawable.setBounds(0, 0, drawableWidth, drawableHeight);` , image dont get shrink and you can see entire image by translating it. Can u please tell some other way ? – Dig Apr 24 '14 at 09:29
  • So if I understand you correctly, you want to have the image drawn in your BlockView, taking up as much space as possible, while maintaining the aspect ratio of the image? – ElDuderino Apr 24 '14 at 18:34
  • yes. i want exactly as you told. – Dig Apr 25 '14 at 04:40

0 Answers0