我想以编程方式将普通矩形图像转换为圆形图像

时间:2012-11-02 16:06:33

标签: android android-image bmp

我想以编程方式将普通矩形图像转换为圆形图像,但不使用xml,请参阅此链接Navigation Drawer (Google+ vs. YouTube)。到目前为止,我按照这个链接How to set bitmap in circular imageview?,但我只是在我的图像上画了一个黑圈。我该怎么办?

2 个答案:

答案 0 :(得分:0)

Bitmap bitmap = BitmapFactory.decodeResource(convertView.getResources(), R.drawable.ic_launcher);
                Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);

                BitmapShader shader = new BitmapShader (bitmap,  TileMode.CLAMP, TileMode.CLAMP);
                Paint paint = new Paint();
                paint.setShader(shader);
                paint.setAntiAlias(true);

                Canvas c = new Canvas(circleBitmap);
                c.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getWidth()/2, paint);

                imgProfilePic.setImageBitmap(circleBitmap);

答案 1 :(得分:0)

public Bitmap dstBmp;
Bitmap getRoundedBitmapnow(Bitmap bitmap) 
{
 //         convert rectangle to square
        if (bitmap.getWidth() >= bitmap.getHeight()){

          dstBmp = Bitmap.createBitmap(
          bitmap, 
          bitmap.getWidth()/2 - bitmap.getHeight()/2,
             0,
             bitmap.getHeight(), 
             bitmap.getHeight()
             );

        }else{

          dstBmp = Bitmap.createBitmap(
          bitmap,
             0, 
             bitmap.getHeight()/2 - bitmap.getWidth()/2,
             bitmap.getWidth(),
             bitmap.getWidth() 
             );
        }
        //          create circle
        Bitmap output = Bitmap.createBitmap(dstBmp.getWidth(),
        dstBmp.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();

        final Rect rect1 = new Rect(0, 0, dstBmp.getWidth(), dstBmp.getHeight());
        final RectF rectF1 = new RectF(rect1);


        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawOval(rectF1, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(dstBmp, rect1, rect1, paint);

        return output;

}