androidbitmapdrawablegradientdrawable

How to show Android SeekBar progressChanged value inside SeekBar thumb?


I want to show the value of the current progress point in the thumb of an Android SeekBar. This is what I have tried so far:

SeekBar progBar = (SeekBar)FindViewById(Resource.Id.seekBar1);
        progBar.ProgressChanged += (object sender, SeekBar.ProgressChangedEventArgs e) =>
        {
            if (e.FromUser)
            {
                Drawable d = ContextCompat.GetDrawable(this, Resource.Drawable.thumb);
                Bitmap bitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.thumb);
                Bitmap bmp = bitmap.Copy(Bitmap.Config.Argb8888, true);// this line gives me a System.NullReferenceException: Object reference not set to an instance of an object. error
                Canvas c = new Canvas(bmp);
                Canvas c = new Canvas(bmp);
                string text = Integer.ToString(progBar.Progress);
                Paint p = new Paint();
                p.SetTypeface(Typeface.DefaultBold);
                p.TextSize = 14;
                p.Color = Color.White;
                int width = (int)p.MeasureText(text);
                int yPos = (int)((c.Height / 2) - ((p.Descent() + p.Ascent()) / 2));
                c.DrawText(text, (bmp.Width - width) / 2, yPos, p);
                progBar.SetThumb(new BitmapDrawable(Resources, bmp));
            }
        };

Then when I got the type of Drawable d, it's a Gradient Drawable. I researched but I couldn't find a way to convert a gradient Drawable to bitmap.


Solution

  • Drawable d = ContextCompat.GetDrawable(this, Resource.Drawable.thumb);
            Canvas c = new Canvas();
            Bitmap bitmap = Bitmap.CreateBitmap(d.IntrinsicWidth, d.IntrinsicHeight, Bitmap.Config.Argb8888);
            c.SetBitmap(bitmap);
            d.SetBounds(0, 0, d.IntrinsicWidth, d.IntrinsicHeight);
            d.Draw(c);
            //Bitmap bmp = bitmap.Copy(Bitmap.Config.Argb8888, true);
            string text = Integer.ToString(progress) + "%";
            Paint p = new Paint();
            p.SetTypeface(Typeface.CreateFromAsset(Assets, "fonts/Brandon_bld.otf"));
            p.TextSize = 18;
            p.Color = Color.White;
            int width = (int)p.MeasureText(text);
            int yPos = (int)((c.Height / 2) - ((p.Descent() + p.Ascent()) / 2));
            c.DrawText(text, (bitmap.Width - width) / 2, yPos, p);
            progBar.SetThumb(new BitmapDrawable(Resources, bitmap));
    

    using the canvas to create the bitmap worked