日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Android實現圓形圖片小工具_Android

作者:Rose?J ? 更新時間: 2022-11-06 編程語言

本文實例為大家分享了Android實現圓形圖片小工具的具體代碼,供大家參考,具體內容如下

1.CircleImageView類代碼

public class CircleImageView extends androidx.appcompat.widget.AppCompatImageView {

? ? //畫筆
? ? private Paint mPaint;
? ? //圓形圖片的半徑
? ? private int mRadius;
? ? //圖片的宿放比例
? ? private float mScale;

? ? public CircleImageView(Context context) {
? ? ? ? super(context);
? ? }

? ? public CircleImageView(Context context, @Nullable AttributeSet attrs) {
? ? ? ? super(context, attrs);
? ? }

? ? public CircleImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
? ? ? ? super(context, attrs, defStyleAttr);
? ? }

? ? @Override
? ? protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
? ? ? ? super.onMeasure(widthMeasureSpec, heightMeasureSpec);
? ? ? ? //由于是圓形,寬高應保持一致
? ? ? ? int size = Math.min(getMeasuredWidth(), getMeasuredHeight());
? ? ? ? mRadius = size / 2;
? ? ? ? setMeasuredDimension(size, size);
? ? }

? ? @SuppressLint("DrawAllocation")
? ? @Override
? ? protected void onDraw(Canvas canvas) {

? ? ? ? mPaint = new Paint();

? ? ? ? Drawable drawable = getDrawable();

? ? ? ? if (null != drawable) {
? ? ? ? ? ? Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();

? ? ? ? ? ? //初始化BitmapShader,傳入bitmap對象
? ? ? ? ? ? BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
? ? ? ? ? ? //計算縮放比例
? ? ? ? ? ? mScale = (mRadius * 2.0f) / Math.min(bitmap.getHeight(), bitmap.getWidth());

? ? ? ? ? ? Matrix matrix = new Matrix();
? ? ? ? ? ? matrix.setScale(mScale, mScale);
? ? ? ? ? ? bitmapShader.setLocalMatrix(matrix);
? ? ? ? ? ? mPaint.setShader(bitmapShader);
? ? ? ? ? ? //畫圓形,指定好坐標,半徑,畫筆
? ? ? ? ? ? canvas.drawCircle(mRadius, mRadius, mRadius, mPaint);
? ? ? ? } else {
? ? ? ? ? ? super.onDraw(canvas);
? ? ? ? }
? ? }

}

2.布局文件中使用

代碼

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
? ? xmlns:app="http://schemas.android.com/apk/res-auto"
? ? xmlns:tools="http://schemas.android.com/tools"
? ? android:layout_width="match_parent"
? ? android:layout_height="match_parent"
? ? tools:context=".MainActivity">

? ?<com.hnucm18jr.myapplication.CircleImageView
? ? ? ?android:layout_width="100dp"
? ? ? ?android:layout_height="100dp"
? ? ? ?android:src="@drawable/a1"
? ? ? ?app:layout_constraintLeft_toLeftOf="parent"
? ? ? ?app:layout_constraintRight_toRightOf="parent"
? ? ? ?app:layout_constraintTop_toTopOf="parent"
? ? ? ?android:layout_marginTop="200dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

原文鏈接:https://blog.csdn.net/qq_46526828/article/details/108928654

欄目分類
最近更新