Sriram C G
Sriram C G

Reputation: 931

To draw Bitmap - Wrap content to Surface view in Android

I have created a custom surface view class with threads and I added the custom surface view in my main activity inside a relative layout. Now I declare a bitmap in the custom surface view class constructor.

public static Bitmap mbitmap;
public Surface(Context ctx, AttributeSet attrSet) {
        super(ctx, attrSet);
        context = ctx;
        mbitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.abc);         
        SurfaceHolder holder = getHolder();
        holder.addCallback(this);
    }

And I have drawn it in canvas

public void doDraw(Canvas canvas) {
    canvas.drawBitmap(mbitmap, 0, 0, null);
}

I get the successful drawing. But it occupies the whole screen

<RelativeLayout
    android:id="@+id/outer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 <com.cg.Surface
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
       <RelativeLayout
        android:id="@+id/processing_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </RelativeLayout>
</RelativeLayout>

even though I use Wrap_Content for Height and Width I get the whole screen drawn at the back. How to draw the bitmap image with appropriate size alone? Is that possible with this override method in Custom Surface View Class :

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height)
{ }

If no how to use setMeasuredDimension within it and restrict the size of surfaceview within the Bitmap?

Upvotes: 2

Views: 4356

Answers (2)

Sriram C G
Sriram C G

Reputation: 931

We can use a rectangle, and draw an image inside it using Matrix, so we can achieve

public void doDraw(Canvas canvas)
{
int width = mbitmap.getWidth();
int height = mbitmap.getHeight();
float h= (float) height;
float w= (float) width;
Matrix mat=new Matrix();
mat.setTranslate( 500, 500 );
mat.setScale(800/w ,800/h);
canvas.drawBitmap(mbitmap, mat, null);
}

Upvotes: 4

Sriram C G
Sriram C G

Reputation: 931

we can achieve that using the

public void drawBitmap (Bitmap bitmap, Rect src, Rect dst, Paint paint); 

I mean :

canvas.drawBitmap(bitmap, src, dst, paint);

method in onDraw with

Rect src = new Rect(0, 0, width, height);
Rect dst = new Rect(x, y, x + width, y + height); 

makes it done I hope. I thought this might help others, since a long time I awaited to reach this solution of myself.

Upvotes: 3

Related Questions