Java Code Examples for android.graphics.Bitmap#setHasAlpha()

The following examples show how to use android.graphics.Bitmap#setHasAlpha() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: giffun   File: LruBitmapPool.java    License: Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
@Override
public synchronized Bitmap getDirty(int width, int height, Bitmap.Config config) {
    // Config will be null for non public config types, which can lead to transformations naively passing in
    // null as the requested config here. See issue #194.
    final Bitmap result = strategy.get(width, height, config != null ? config : DEFAULT_CONFIG);
    if (result == null) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "Missing bitmap=" + strategy.logBitmap(width, height, config));
        }
        misses++;
    } else {
        hits++;
        currentSize -= strategy.getSize(result);
        tracker.remove(result);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
            result.setHasAlpha(true);
        }
    }
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "Get bitmap=" + strategy.logBitmap(width, height, config));
    }
    dump();

    return result;
}
 
Example 2
Source Project: Telegram   File: Bitmaps.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static Bitmap createBitmap(int width, int height, Bitmap.Config config) {
    Bitmap bitmap;
    if (Build.VERSION.SDK_INT < 21) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inDither = true;
        options.inPreferredConfig = config;
        options.inPurgeable = true;
        options.inSampleSize = 1;
        options.inMutable = true;
        byte[] array = jpegData.get();
        array[76] = (byte) (height >> 8);
        array[77] = (byte) (height & 0x00ff);
        array[78] = (byte) (width >> 8);
        array[79] = (byte) (width & 0x00ff);
        bitmap = BitmapFactory.decodeByteArray(array, 0, array.length, options);
        Utilities.pinBitmap(bitmap);
        bitmap.setHasAlpha(true);
        bitmap.eraseColor(0);
    } else {
        bitmap = Bitmap.createBitmap(width, height, config);
    }
    if (config == Bitmap.Config.ARGB_8888 || config == Bitmap.Config.ARGB_4444) {
        bitmap.eraseColor(Color.TRANSPARENT);
    }
    return bitmap;
}
 
Example 3
public static Bitmap createBitmap(int width, int height, Bitmap.Config config) {
    Bitmap bitmap;
    if (Build.VERSION.SDK_INT < 21) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inDither = true;
        options.inPreferredConfig = config;
        options.inPurgeable = true;
        options.inSampleSize = 1;
        options.inMutable = true;
        byte[] array = jpegData.get();
        array[76] = (byte) (height >> 8);
        array[77] = (byte) (height & 0x00ff);
        array[78] = (byte) (width >> 8);
        array[79] = (byte) (width & 0x00ff);
        bitmap = BitmapFactory.decodeByteArray(array, 0, array.length, options);
        Utilities.pinBitmap(bitmap);
        bitmap.setHasAlpha(true);
        bitmap.eraseColor(0);
    } else {
        bitmap = Bitmap.createBitmap(width, height, config);
    }
    if (config == Bitmap.Config.ARGB_8888 || config == Bitmap.Config.ARGB_4444) {
        bitmap.eraseColor(Color.TRANSPARENT);
    }
    return bitmap;
}
 
Example 4
Source Project: fresco   File: PlatformBitmapFactory.java    License: MIT License 6 votes vote down vote up
/**
 * Creates a bitmap with the specified width and height. Its initial density is determined from
 * the given DisplayMetrics.
 *
 * @param display Display metrics for the display this bitmap will be drawn on
 * @param width The width of the bitmap
 * @param height The height of the bitmap
 * @param config The bitmap config to create
 * @param hasAlpha If the bitmap is ARGB_8888 this flag can be used to mark the bitmap as opaque
 *     Doing so will clear the bitmap in black instead of transparent
 * @param callerContext the Tag to track who create the Bitmap
 * @return a reference to the bitmap
 * @throws IllegalArgumentException if the width or height are <= 0
 * @throws TooManyBitmapsException if the pool is full
 * @throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated
 */
private CloseableReference<Bitmap> createBitmap(
    DisplayMetrics display,
    int width,
    int height,
    Bitmap.Config config,
    boolean hasAlpha,
    @Nullable Object callerContext) {
  checkWidthHeight(width, height);
  CloseableReference<Bitmap> bitmapRef = createBitmapInternal(width, height, config);

  Bitmap bitmap = bitmapRef.get();
  if (display != null) {
    bitmap.setDensity(display.densityDpi);
  }

  if (Build.VERSION.SDK_INT >= 12) {
    bitmap.setHasAlpha(hasAlpha);
  }

  if (config == Bitmap.Config.ARGB_8888 && !hasAlpha) {
    bitmap.eraseColor(0xff000000);
  }

  return bitmapRef;
}
 
Example 5
Source Project: Autoinstall   File: BitmapUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Fills the bitmap's pixels of the specified Color to transparency.
 * 
 * @param aBitmap bitmap to process
 * @param aColor color to fill
 * @return bmp
 */
@SuppressLint("NewApi")
public static Bitmap eraseBG(Bitmap aBitmap, int aColor) {
    int width = aBitmap.getWidth();
    int height = aBitmap.getHeight();
    Bitmap b = aBitmap.copy(Config.ARGB_8888, true);
       if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR1) {
           b.setHasAlpha(true);
       }

    int[] pixels = new int[width * height];
    aBitmap.getPixels(pixels, 0, width, 0, 0, width, height);

    for (int i = 0; i < width * height; i++) {
        if (pixels[i] == aColor) {
            pixels[i] = 0;
        }
    }

    b.setPixels(pixels, 0, width, 0, 0, width, height);

    return b;
}
 
Example 6
Source Project: KrGallery   File: Bitmaps.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static Bitmap createBitmap(int width, int height, Bitmap.Config config) {
    Bitmap bitmap;
    if (Build.VERSION.SDK_INT < 21) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inDither = true;
        options.inPreferredConfig = config;
        options.inPurgeable = true;
        options.inSampleSize = 1;
        options.inMutable = true;
        byte[] array = jpegData.get();
        array[76] = (byte) (height >> 8);
        array[77] = (byte) (height & 0x00ff);
        array[78] = (byte) (width >> 8);
        array[79] = (byte) (width & 0x00ff);
        bitmap = BitmapFactory.decodeByteArray(array, 0, array.length, options);
        Utilities.pinBitmap(bitmap);
        bitmap.setHasAlpha(true);
        bitmap.eraseColor(0);
    } else {
        bitmap = Bitmap.createBitmap(width, height, config);
    }
    if (config == Bitmap.Config.ARGB_8888 || config == Bitmap.Config.ARGB_4444) {
        bitmap.eraseColor(Color.TRANSPARENT);
    }
    return bitmap;
}
 
Example 7
@Override
protected Bitmap transform(@NonNull Context context, @NonNull BitmapPool pool,
                           @NonNull Bitmap toTransform, int outWidth, int outHeight) {
    int width = toTransform.getWidth();
    int height = toTransform.getHeight();
    int currentHeight = outHeight;
    int currentWidth = outWidth;
    if (viewWidth > -1) {
        currentWidth = viewWidth;
    }

    if (viewHeight > -1) {
        currentHeight = viewHeight;
    }

    Bitmap bitmap = pool.get(currentWidth, currentHeight, Bitmap.Config.ARGB_8888);
    bitmap.setHasAlpha(true);
    Canvas canvas = new Canvas(bitmap);

    Paint paint = new Paint();
    paint.setAntiAlias(true);

    paint.setShader(new BitmapShader(toTransform, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
    drawRoundRect(canvas, paint, currentWidth, currentHeight);
    return bitmap;
}
 
Example 8
Source Project: fresco   File: PlatformBitmapFactory.java    License: MIT License 5 votes vote down vote up
/**
 * Set some property of the source bitmap to the destination bitmap
 *
 * @param source the source bitmap
 * @param destination the destination bitmap
 */
private static void setPropertyFromSourceBitmap(Bitmap source, Bitmap destination) {
  // The new bitmap was created from a known bitmap source so assume that
  // they use the same density
  destination.setDensity(source.getDensity());
  if (Build.VERSION.SDK_INT >= 12) {
    destination.setHasAlpha(source.hasAlpha());
  }

  if (Build.VERSION.SDK_INT >= 19) {
    destination.setPremultiplied(source.isPremultiplied());
  }
}
 
Example 9
Source Project: DaVinci   File: DiskLruImageCache.java    License: Apache License 2.0 5 votes vote down vote up
public Bitmap getBitmap(String key) {

        Bitmap bitmap = null;
        DiskLruCache.Snapshot snapshot = null;
        try {

            snapshot = mDiskCache.get(key);
            if (snapshot == null) {
                return null;
            }
            final InputStream in = snapshot.getInputStream(0);
            if (in != null) {
                final BufferedInputStream buffIn =
                        new BufferedInputStream(in, IO_BUFFER_SIZE);

                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                options.inPremultiplied = true;
                bitmap = BitmapFactory.decodeStream(buffIn,null,options);
                bitmap.setHasAlpha(true);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (snapshot != null) {
                snapshot.close();
            }
        }

        Log.d(TAG, bitmap == null ? "" : "image read from disk " + key);

        return bitmap;

    }
 
Example 10
Source Project: DaVinci   File: DiskLruImageCache.java    License: Apache License 2.0 5 votes vote down vote up
private boolean writeBitmapToFile(Bitmap bitmap, DiskLruCache.Editor editor)
        throws IOException, FileNotFoundException {
    OutputStream out = null;
    try {
        bitmap.setHasAlpha(true);
        //bitmap.setConfig(Bitmap.Config.ARGB_8888);
        out = new BufferedOutputStream(editor.newOutputStream(0), IO_BUFFER_SIZE);
        return bitmap.compress(mCompressFormat, mCompressQuality, out);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}
 
Example 11
Source Project: fresco   File: DefaultImageDecoder.java    License: MIT License 5 votes vote down vote up
private void maybeApplyTransformation(
    @Nullable BitmapTransformation transformation, CloseableReference<Bitmap> bitmapReference) {
  if (transformation == null) {
    return;
  }
  Bitmap bitmap = bitmapReference.get();
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1
      && transformation.modifiesTransparency()) {
    bitmap.setHasAlpha(true);
  }
  transformation.transform(bitmap);
}
 
Example 12
Source Project: fresco   File: FrescoVitoRegionDecoder.java    License: MIT License 5 votes vote down vote up
private void maybeApplyTransformation(
    @Nullable BitmapTransformation transformation, CloseableReference<Bitmap> bitmapReference) {
  if (transformation == null) {
    return;
  }
  Bitmap bitmap = bitmapReference.get();
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1
      && transformation.modifiesTransparency()) {
    bitmap.setHasAlpha(true);
  }
  transformation.transform(bitmap);
}
 
Example 13
Source Project: giffun   File: GifDecoder.java    License: Apache License 2.0 4 votes vote down vote up
@TargetApi(12)
private static void setAlpha(Bitmap bitmap) {
    if (Build.VERSION.SDK_INT >= 12) {
        bitmap.setHasAlpha(true);
    }
}
 
Example 14
Source Project: sketch   File: GifDrawable.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Retrieves a copy of currently buffered frame.
 *
 * @return current frame
 */
public Bitmap getCurrentFrame() {
	final Bitmap copy = mBuffer.copy(mBuffer.getConfig(), mBuffer.isMutable());
	copy.setHasAlpha(mBuffer.hasAlpha());
	return copy;
}
 
Example 15
Source Project: PdfBox-Android   File: JPEGFactoryTest.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Tests ARGB JPEGFactory#createFromImage(PDDocument document, BufferedImage
 * image)
 */
@Test
public void testCreateFromImageARGB_4444() throws IOException
{
    // workaround Open JDK bug
    // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=7044758
    if (System.getProperty("java.runtime.name").equals("OpenJDK Runtime Environment")
        && (System.getProperty("java.specification.version").equals("1.6")
        || System.getProperty("java.specification.version").equals("1.7")
        || System.getProperty("java.specification.version").equals("1.8")))
    {
        return;
    }

    PDDocument document = new PDDocument();
    Bitmap image = BitmapFactory.decodeStream(testContext.getAssets().open(
        "pdfbox/com/tom_roush/pdfbox/pdmodel/graphics/image/jpeg.jpg"));

    // create an ARGB image
    int width = image.getWidth();
    int height = image.getHeight();
    Bitmap argbImage = image.copy(Bitmap.Config.ARGB_4444, true);
    argbImage.setHasAlpha(true);

    int[] argbPixels = new int[width * height];
    argbImage.getPixels(argbPixels, 0, width, 0, 0, width, height);
    for (int x = 0; x < argbImage.getWidth(); ++x)
    {
        for (int y = 0; y < argbImage.getHeight(); ++y)
        {
            argbPixels[x + width * y] =
                (argbPixels[x + width * y] & 0xFFFFFF) | ((y / 10 * 10) << 24);
        }
    }
    argbImage.setPixels(argbPixels, 0, width, 0, 0, width, height);

    PDImageXObject ximage = JPEGFactory.createFromImage(document, argbImage);
    validate(ximage, 8, width, height, "jpg",
        PDDeviceRGB.INSTANCE.getName());
    assertNotNull(ximage.getSoftMask());
    // TODO: PdfBox-Android should be "jpg", but we're using FLATE for the alpha
    validate(ximage.getSoftMask(), 8, width, height, "png",
        PDDeviceGray.INSTANCE.getName());
    assertTrue(colorCount(ximage.getSoftMask().getImage()) >= 16);

    doWritePDF(document, ximage, testResultsDir, "jpeg-4bargb.pdf");
}
 
Example 16
Source Project: PdfBox-Android   File: JPEGFactoryTest.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Tests ARGB JPEGFactory#createFromImage(PDDocument document, BufferedImage
 * image)
 */
@Test
public void testCreateFromImageARGB_8888() throws IOException
{
    // workaround Open JDK bug
    // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=7044758
    if (System.getProperty("java.runtime.name").equals("OpenJDK Runtime Environment")
        && (System.getProperty("java.specification.version").equals("1.6")
        || System.getProperty("java.specification.version").equals("1.7")
        || System.getProperty("java.specification.version").equals("1.8")))
    {
        return;
    }

    PDDocument document = new PDDocument();
    Bitmap image = BitmapFactory.decodeStream(testContext.getAssets().open(
        "pdfbox/com/tom_roush/pdfbox/pdmodel/graphics/image/jpeg.jpg"));

    // create an ARGB image
    int width = image.getWidth();
    int height = image.getHeight();
    Bitmap argbImage = image.copy(Bitmap.Config.ARGB_8888, true);
    argbImage.setHasAlpha(true);

    int[] argbPixels = new int[width * height];
    argbImage.getPixels(argbPixels, 0, width, 0, 0, width, height);
    for (int x = 0; x < argbImage.getWidth(); ++x)
    {
        for (int y = 0; y < argbImage.getHeight(); ++y)
        {
            argbPixels[x + width * y] =
                (argbPixels[x + width * y] & 0xFFFFFF) | ((y / 10 * 10) << 24);
        }
    }
    argbImage.setPixels(argbPixels, 0, width, 0, 0, width, height);

    PDImageXObject ximage = JPEGFactory.createFromImage(document, argbImage);
    validate(ximage, 8, width, height, "jpg",
        PDDeviceRGB.INSTANCE.getName());
    assertNotNull(ximage.getSoftMask());
    // TODO: PdfBox-Android should be "jpg", but we're using FLATE for the alpha
    validate(ximage.getSoftMask(), 8, width, height, "png",
        PDDeviceGray.INSTANCE.getName());
    assertTrue(colorCount(ximage.getSoftMask().getImage()) > image.getHeight() / 10);

    doWritePDF(document, ximage, testResultsDir, "jpeg-intargb.pdf");
}
 
Example 17
Source Project: GifImageView   File: GifDecoder.java    License: MIT License 4 votes vote down vote up
@TargetApi(12)
private static void setAlpha(Bitmap bitmap) {
  if (Build.VERSION.SDK_INT >= 12) {
    bitmap.setHasAlpha(true);
  }
}
 
Example 18
/**
 * Takes Reboot screenshot of the current display and shows an animation.
 */
@SuppressLint("NewApi")
public void takeScreenshot(Context context, String fileFullPath)
{
    if(fileFullPath == ""){
        format = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = format.format(new Date(System.currentTimeMillis())) + ".png";
        fileFullPath = "/data/local/tmp/" + fileName;
    }

    if(ShellUtils.checkRootPermission()){
        if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH){
            ShellUtils.execCommand("/system/bin/screencap -p "+ fileFullPath,true);
        }
    }
    else {
        if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2 && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH){
            wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            mDisplay = wm.getDefaultDisplay();
            mDisplayMatrix = new Matrix();
            mDisplayMetrics = new DisplayMetrics();
            // We need to orient the screenshot correctly (and the Surface api seems to take screenshots
            // only in the natural orientation of the device :!)
            mDisplay.getRealMetrics(mDisplayMetrics);
            float[] dims =
                    {
                            mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels
                    };
            float degrees = getDegreesForRotation(mDisplay.getRotation());
            boolean requiresRotation = (degrees > 0);
            if (requiresRotation)
            {
                // Get the dimensions of the device in its native orientation
                mDisplayMatrix.reset();
                mDisplayMatrix.preRotate(-degrees);
                mDisplayMatrix.mapPoints(dims);
                dims[0] = Math.abs(dims[0]);
                dims[1] = Math.abs(dims[1]);
            }

            Bitmap mScreenBitmap = screenShot((int) dims[0], (int) dims[1]);
            if (requiresRotation)
            {
                // Rotate the screenshot to the current orientation
                Bitmap ss = Bitmap.createBitmap(mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels,
                        Bitmap.Config.ARGB_8888);
                Canvas c = new Canvas(ss);
                c.translate(ss.getWidth() / 2, ss.getHeight() / 2);
                c.rotate(degrees);
                c.translate(-dims[0] / 2, -dims[1] / 2);
                c.drawBitmap(mScreenBitmap, 0, 0, null);
                c.setBitmap(null);
                mScreenBitmap = ss;
                if (ss != null && !ss.isRecycled())
                {
                    ss.recycle();
                }
            }

            // If we couldn't take the screenshot, notify the user
            if (mScreenBitmap == null)
            {
                Toast.makeText(context, "screen shot fail", Toast.LENGTH_SHORT).show();
            }

            // Optimizations
            mScreenBitmap.setHasAlpha(false);
            mScreenBitmap.prepareToDraw();

            saveBitmap2file(context, mScreenBitmap, fileFullPath);
        }
    }

}
 
Example 19
Source Project: Hentoid   File: ResizeBitmapHelper.java    License: Apache License 2.0 4 votes vote down vote up
static Bitmap resizeNice(@NonNull final RenderScript rs, final Bitmap src, float xScale, float yScale) {
        // Calculate gaussian's radius
        float sigma = (1 / xScale) / (float) Math.PI;
        // https://android.googlesource.com/platform/frameworks/rs/+/master/cpu_ref/rsCpuIntrinsicBlur.cpp
        float radius = 2.5f * sigma/* - 1.5f*/; // Works better that way
        radius = Math.min(25, Math.max(0.0001f, radius));
        Timber.d(">> using sigma=%s for xScale=%s => radius=%s", sigma, xScale, radius);

        // Defensive programming in case the threading/view recycling recycles a bitmap just before that methods is reached
        if (null == src || src.isRecycled()) return src;

        Bitmap.Config bitmapConfig = src.getConfig();
        int srcWidth = src.getWidth();
        int srcHeight = src.getHeight();
        int dstWidth = Math.round(srcWidth * xScale);
        int dstHeight = Math.round(srcHeight * yScale);
        src.setHasAlpha(false);

        // Gaussian filter
        Allocation tmpIn = Allocation.createFromBitmap(rs, src);
        Allocation tmpFiltered = Allocation.createTyped(rs, tmpIn.getType());
        ScriptIntrinsicBlur blurInstrinsic = ScriptIntrinsicBlur.create(rs, tmpIn.getElement());

        blurInstrinsic.setRadius(radius);
        blurInstrinsic.setInput(tmpIn);
        blurInstrinsic.forEach(tmpFiltered);

        src.recycle();
        tmpIn.destroy();
        blurInstrinsic.destroy();


        // Resize
        Bitmap dst = Bitmap.createBitmap(dstWidth, dstHeight, bitmapConfig);
        Type t = Type.createXY(rs, tmpFiltered.getElement(), dstWidth, dstHeight);
        Allocation tmpOut = Allocation.createTyped(rs, t);
        ScriptIntrinsicResize resizeIntrinsic = ScriptIntrinsicResize.create(rs);

        resizeIntrinsic.setInput(tmpFiltered);
        resizeIntrinsic.forEach_bicubic(tmpOut);
        tmpOut.copyTo(dst);

        tmpFiltered.destroy();
        resizeIntrinsic.destroy();
        tmpOut.destroy();
/*
        // Additional sharpen script just in case (WIP)
        Allocation tmpSharpOut = Allocation.createTyped(rs, t);
        //ScriptIntrinsicConvolve3x3 sharpen = ScriptIntrinsicConvolve3x3.create(rs, tmpOut.getElement());
        ScriptIntrinsicConvolve3x3 sharpen = ScriptIntrinsicConvolve3x3.create(rs, Element.U8_4(rs));
        sharpen.setCoefficients(getSharpenCoefficients());
        sharpen.setInput(tmpOut);
        sharpen.forEach(tmpSharpOut);

        tmpSharpOut.copyTo(dst);

        tmpOut.destroy();
        tmpSharpOut.destroy();
        sharpen.destroy();
*/

        return dst;
    }
 
Example 20
Source Project: Android-BadgedImageView   File: BadgeDrawable.java    License: MIT License 4 votes vote down vote up
public BadgeDrawable(Context context, String text) {
    this.text = text;

    final DisplayMetrics dm = context.getResources().getDisplayMetrics();

    final float density = dm.density;
    final float scaledDensity = dm.scaledDensity;
    final float padding = PADDING * density;
    final float cornerRadius = CORNER_RADIUS * density;

    final Rect textBounds = new Rect();
    final TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint
            .SUBPIXEL_TEXT_FLAG);
    textPaint.setTypeface(Typeface.create(TYPEFACE, TYPEFACE_STYLE));
    textPaint.setTextSize(TEXT_SIZE * scaledDensity);
    textPaint.getTextBounds(text, 0, text.length(), textBounds);

    height = (int) (padding + textBounds.height() + padding);
    width = (int) (padding + textBounds.width() + padding);

    if (bitmaps.get(text) == null) {

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setHasAlpha(true);

        final Canvas canvas = new Canvas(bitmap);
        final Paint backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        backgroundPaint.setColor(BACKGROUND_COLOR);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            canvas.drawRoundRect(0, 0, width, height, cornerRadius, cornerRadius,
                    backgroundPaint);
        } else {
            canvas.drawRect(0, 0, width, height, backgroundPaint);
        }

        // punch out the text leaving transparency
        textPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        canvas.drawText(text, padding, height - padding, textPaint);

        bitmaps.put(text, bitmap);
    }

    paint = new Paint();
}