Android --- 自定义ImageView 实现圆形图片
自定義ImageView實現圓形圖片,主要是在onDraw()方法中實現繪制圓形圖片,在onMeasure()中測量圓形的半徑并設置View的寬高。效果如下圖
代碼如下
public class CircleImageView extends ImageView { <span style="color:rgb(128,128,128);">//畫筆 private Paint mPaint;
//圓形圖片的半徑
private int mRadius;
//圖片的宿放比例
private float mScale;
public CircleImageView(Context context) {
super(context);
}
}
<span style="color:rgb(204,120,50);">public </span><span style="color:rgb(255,198,109);">CircleImageView</span>(Context context<span style="color:rgb(204,120,50);">, </span><span style="color:rgb(187,181,41);">@Nullable </span>AttributeSet attrs<span style="color:rgb(204,120,50);">, int </span>defStyleAttr) {<span style="color:rgb(204,120,50);">super</span>(context<span style="color:rgb(204,120,50);">, </span>attrs<span style="color:rgb(204,120,50);">, </span>defStyleAttr)<span style="color:rgb(204,120,50);">;}
<span style="color:rgb(187,181,41);">@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//由于是圓形,寬高應保持一致
int size = Math.min(getMeasuredWidth(), getMeasuredHeight());
mRadius = size / 2;
setMeasuredDimension(size, size);
}
protected void onDraw(Canvas canvas) {
<span style="color:rgb(152,118,170);">mPaint </span>= <span style="color:rgb(204,120,50);">new </span>Paint()<span style="color:rgb(204,120,50);">;
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);
}
}
}
自定義好之后,就可以直接在xml布局中使用該控件
<RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”xmlns:tools=“http://schemas.android.com/tools”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:gravity=“center”
tools:context=“com.sun.zh.bezier.MainActivity”>
<com.sun.zh.bezier.view.CircleImageView
android:id="@+id/image"
android:layout_width=“200dp”
android:layout_height=“200dp”
android:scaleType=“centerCrop”
android:src="@drawable/ic_timg" />
</RelativeLayout>
注意必須設置src圖,設置background圖不會出現圓形效果
在ImageView中src與background的區別:
background會根據ImageView組件給定的長寬進行拉伸,而src就存放的是原圖的大小,不會進行拉伸。src是圖片內容(前景),bg是背景,可以同時使用。此外scaleType只是對src起作用,bg可設置透明度。在動態加載圖片中設置src可使用image.setImageResource(R.drawable.**)。
總結
以上是生活随笔為你收集整理的Android --- 自定义ImageView 实现圆形图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java 文件字符输入流FileRead
- 下一篇: Android --- Bundle实现