GuilhE
GuilhE

Reputation: 11901

ImageView setImageBitmap() from View

I'm doing some experiments and I'm trying to do something like this:

public class MyActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyImageView view = new MyImageView(this);
        setContentView(view);
    }
}


public class MyImageView extends ImageView {

    public MyImageView(Context context) {
        super(context);
        View view = View.inflate(context, R.layout.my_view, null);
        ((TextView) view.findViewById(R.id.view_label)).setText(...);

        Bitmap bitmap = Bitmap.createBitmap(50, 50, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bitmap);
        view.draw(c);

        setImageBitmap(bitmap);
    }
}

My R.layout.my_view layout file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="30dp"
              android:layout_height="30dp"
              android:background="@drawable/blue_spot"
              android:gravity="center">

    <TextView
            tools:text="99"
            android:id="@+id/view_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white"
            android:textStyle="bold"/>
</LinearLayout>

My shape:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="oval">
    <corners android:radius="10dp"/>
    <solid android:color="#5AB7FF"/>
</shape>

And I get a blank empty screen... any idea why?
I'm doing all this workarounds because later I want to do use myImageView.setImageMatrix().
Thanks.

Upvotes: 1

Views: 1153

Answers (1)

GuilhE
GuilhE

Reputation: 11901

Ok I got the problem. It's drawing nothing because that view hasn't been rendered. What I need is a way to render this view without drawing it (in canvas) and then draw that view to the bitmap. That can be achieved using:

view.setDrawingCacheEnabled(true);
view.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);

Now I just have to do some adjustments but I've got it drawn.
Thanks.

Upvotes: 1

Related Questions