Android生成圆形缩略图的一种方法

本文介绍了一种简化方法来将方形头像图片转换为圆形drawable对象,适用于Android Actionbar导航图标。通过使用Bitmap和RoundedBitmapDrawable,可以轻松调整图片大小并保持圆形外观。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

做项目的过程中需将用户头像图片生成圆形的指定大小的drawable对象,用作actionbar的navigation icon。

原始图片是方形的,尺寸144x144,若是直接调用setNavigationIcon()方法,图片将覆盖actionbar的大部分。

综合网上各种制作缩略图和圆形图片的方法,总结出如下个人觉得比较简便的方法,记录下来以备后边用到。

比较简单,直接贴代码

 /**
     * generate scaled circle view from drawable resources
     * @param pContext application context
     * @param pRes drawable resources id
     * @param pRadius Radius of generated view,it will be scaled to this size
     * @return Drawable the circel view with specified radius
     */
    public static Drawable generateScaledCircleDrawable(Context pContext,int pRes,int pRadius){
        Bitmap bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(pContext.getResources(),
                pRes),2*pRadius,2*pRadius,false);
        RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(pContext.getResources(), bitmap);
        drawable.setCornerRadius(pRadius);//设置圆角半径,当圆角半径为宽高的一半时即生成圆形图形
        return drawable;
    }

    /**
     * generate scaled circle view from drawable resources
     * @param pContext application context
     * @param pBitmap bitmap used to generate circle drawable
     * @param pRadius Radius of generated view,it will be scaled to this size
     * @return Drawable the circel view with specified radius
     */
    public static Drawable generateScaledCircleDrawable(Context pContext,Bitmap pBitmap,int pRadius){
        Bitmap bitmap = Bitmap.createScaledBitmap(pBitmap,2*pRadius,2*pRadius,false);
        RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(pContext.getResources(), bitmap);
        drawable.setCornerRadius(pRadius);
        return drawable;
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值