亲宝软件园·资讯

展开

Android圆形图片效果 Android实现圆形图片效果

JH学编程 人气:0
想了解Android实现圆形图片效果的相关内容吗,JH学编程在本文为您仔细讲解Android圆形图片效果的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,圆形图片,下面大家一起来学习吧。

创建RoundPicture.java文件

在src/main/java/XX包下新建RoundPicture.java

写入RoundPicture.java文件

复制下方代码,并引入类即可

public class RoundPicture extends androidx.appcompat.widget.AppCompatImageView {
    private Paint paint;
    public RoundPicture(Context context) {
        this(context, null);
    }
    public RoundPicture(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundPicture(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        paint = new Paint();
    }

//    绘制圆形图片
    @Override
    protected void onDraw(Canvas canvas) {
        Drawable drawable = getDrawable();
        if (null != drawable) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            Bitmap b = getCircleBitmap(bitmap, 14);
            final Rect rectSrc = new Rect(0, 0, b.getWidth(), b.getHeight());
            final Rect rectDest = new Rect(0, 0, getWidth(), getHeight());
            paint.reset();
            canvas.drawBitmap(b, rectSrc, rectDest, paint);
        } else {
            super.onDraw(canvas);
        }
    }
//     获取圆形图片方法
    private Bitmap getCircleBitmap(Bitmap bitmap, int pixels) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        int x = bitmap.getWidth();
        canvas.drawCircle(x / 2, x / 2, x / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }
}

调用RoundPicture创建圆形图片

只需在.xml文件中插入图片处,将控件名改为
< XX.RoundPicture 并引入图片即可

<com.example.jh_android.RoundPicture
            android:id="@+id/iv"
            android:layout_height="200dp"
            android:layout_width="200dp"
            android:layout_marginTop="150dp"
            android:layout_centerHorizontal="true"
            android:src="@drawable/head"
    />

加载全部内容

相关教程
猜你喜欢
用户评论