2

I need to create a completely round image in Android. I've got the following code which works in newer version of Android, but in older versions (2.3), it is just a black circle:

    Bitmap avatar = null;
    if (avatarUrl == null || avatarUrl.equals("")) {
        avatar = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_no_avatar);
    } else {
        avatar = HttpClientHelper.downloadImage(avatarUrl); 
    }

    if (avatar == null) {
        // No avatar? Load the default one and use it instead
        avatar = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_no_avatar);
    }

    float width = 50; // avatar.getWidth();
    float height = 50; // avatar.getHeight();
    float ratio = (float)avatar.getWidth() / (float)avatar.getHeight();

    // Scale the avatar to the area that it needs to fit into
    avatar = Bitmap.createScaledBitmap(avatar, (int)(width * ratio), (int)height, true);

    // Turn the avatar into a round image       
    Bitmap circleBitmap = Bitmap.createBitmap((int)width, (int)height, Bitmap.Config.ARGB_8888);        

    BitmapShader shader = new BitmapShader(avatar, TileMode.CLAMP, TileMode.CLAMP);
    Paint paint = new Paint();
    paint.setShader(shader);

    RectF rect = new RectF(0.0f, 0.0f, width, height);          
    Canvas c = new Canvas(circleBitmap);
    c.drawCircle(width / 2, height / 2, (width / 2) - 1, paint);

Is there something different I should do with 2.3 to make this work?

2 Answers 2

0

Use this

              float width = 50; // avatar.getWidth();
                  float height = 50; // avatar.getHeight();
                  float radius = 45;
                Bitmap bmpBG = Bitmap.createBitmap(width, height,
                    Bitmap.Config.ARGB_8888);


            Canvas c = new Canvas(bmpBG);

//YOU CAN ADD SHADER FOR EFFECTS

            Paint p = new Paint();
            p.setAntiAlias(true);
            p.setDither(true);

            p.setColor(Color.RED);//SET YOUR COLOR HERE

            c.drawCircle(width/ 2, height/ 2,
                    radius , p);

    //NOW USE bmpBG 
0

This must be a bug in 2.3. I was previously setting the round bitmap as the ImageView background which caused the black circle. When I set it as the foreground, the problem went away.

Again, this only happens with 2.3. After 3.0 this problem no longer exists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.