Search code examples
javaandroidandroid-studioandroid-drawable

How to add text to a drawable


I want to edit an image by adding text on top of an existing image. I tried this, but the drawable in the ImageView disappears:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    Button btnAdd=(Button) findViewById(R.id.btnAdd);
    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText firstNum=(EditText)findViewById(R.id.fisrtNum);
            EditText secondNum=(EditText)findViewById(R.id.secondNum);
            TextView sumTV=(TextView)findViewById(R.id.sumTV);
            ImageView picIV=(ImageView) findViewById(R.id.picIV);

            Bitmap bitmap = Bitmap.createBitmap(300, 200, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

            paint.setTextSize(42);
            paint.setTextAlign(Paint.Align.CENTER);
            canvas.drawText("hello world",150,30,paint);
            paint.setColor(Color.BLUE);
            canvas.drawCircle(50, 50, 10, paint);
            picIV.setImageBitmap(bitmap);

            picIV.setImageDrawable(new BitmapDrawable(getResources(), bitmap));
            sumTV.setText(result+"");

        }
    }
}

Thank you in advance for helping find a solution. My goal is to be able to edit an image and to send it to other apps.


Solution

  • Thanks for the link. Very helpful. Turns out i was not declaring my Bitmap correctly.

    This solved the problem

                picIV.buildDrawingCache();
                Bitmap bitmap= picIV.getDrawingCache();
    

    Its a deprecated method, but it works.