Image getting stretched when displayed in rounded imageview

前端 未结 2 1532
太阳男子
太阳男子 2020-12-31 22:13

Below is my RoundedImageView class that extends ImageView:

public class RoundedImageView extends ImageView {

public RoundedImageView(Context context) {
             


        
相关标签:
2条回答
  • 2020-12-31 22:48

    You should resize your bitmap by its width/height rate.

    ----EDITED---- This will be a more flexible way to do it.

    @Override
    protected void onDraw(Canvas canvas) {
    
        Drawable drawable = getDrawable();
    
        if (drawable == null) {
            return;
        }
    
        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
    
        int w = getWidth(), h = getHeight();
        int radius = w < h ? w : h;
    
        Bitmap roundBitmap = getCroppedBitmap(bitmap, radius, w, h);
        // roundBitmap= ImageUtils.setCircularInnerGlow(roundBitmap, 0xFFBAB399,
        // 4, 1);
        canvas.drawBitmap(roundBitmap, 0, 0, null);
    
    }
    
    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius, int w, int h) {
        Bitmap sbmp;
        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float _w_rate = 1.0f * radius / bmp.getWidth();
            float _h_rate = 1.0f * radius / bmp.getHeight();
            float _rate = _w_rate < _h_rate ? _h_rate : _w_rate;
            sbmp = Bitmap.createScaledBitmap(bmp, (int)(bmp.getWidth() * _rate), (int)(bmp.getHeight() * _rate), false);
        }
        else
            sbmp = bmp;
    
        Bitmap output = Bitmap.createBitmap(sbmp.getWidth(), sbmp.getHeight(),
                Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
    
        final int color = 0xffa19774;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, sbmp.getWidth(), sbmp.getHeight());
    
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor("#BAB399"));
        canvas.drawCircle(w / 2, h / 2, (w < h ? w : h) / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);
    
        return output;
    }
    
    0 讨论(0)
  • 2020-12-31 23:00

    Another alternative is to create a transparent PNG for the border (a hollowed out circle in a square) and place it as the background of a view directly above, and with the same dimensions, of the ImageView.

    Something like this:

    Round Image Border

    EDIT:

    Seems white on white images are porblematic :) (trust me, there's an image there...) So I uplaoded 2 more:

    enter image description here enter image description here

    0 讨论(0)
提交回复
热议问题