Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

利用 Android BitmapShader 製作自帶邊框的圓形頭像

編輯:關於 Android 程式設計

效果如下:

BitmapShader 簡單介紹

BitmapShader 的主要作用是透過 Paint 對畫布進行指定的 Bitmap 填充,實現一系列效果,有三種模式可選:

1. CLAMP-拉伸:不斷重複圖片最後一個元素,圖片較小而繪製面積較大時明顯。
2. REPEAT-重複:橫向縱向不斷重複。
3. MIRROR-翻轉:像折紙一樣翻轉著重複。

本文使用 CLAMP 模式,只要控制好圖形大小就能避免拉伸。

具體實現

為了自定義圖像、邊框寬度與顏色,先在 res/values 下新建 attrs.xml:

 <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyCustomView"> <attr name="mborder_color" format="color"></attr> <attr name="mborder_width" format="dimension"></attr> <attr name="msrc" format="reference"></attr> </declare-styleable> </resources>

接著在自定義 View 中解析這些屬性:

 TypedArray type = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView); mBorderColor = type.getColor(R.styleable.MyCustomView_mborder_color,0); mDrawable = type.getDrawable(R.styleable.MyCustomView_msrc); BitmapDrawable bitmapDrawable = (BitmapDrawable) mDrawable; mBitmap = bitmapDrawable.getBitmap(); mBorderWidth = type.getDimensionPixelSize(R.styleable.MyCustomView_mborder_width, 2);

注意 msrc 解析得到的是 Drawable,需轉為 Bitmap。接著用 Bitmap 繪製圓形頭像,初始化 BitmapShader 與 Paint:

 mSrcBitmap = Bitmap.createScaledBitmap(mBitmap, mWidth, mHeight, false); mShader = new BitmapShader(mSrcBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mPaint = new Paint(); mPaint.setShader(mShader); mRadius = (mWidth - mBorderWidth * 2 - 4) / 2; mCircleX = (mWidth) / 2; mCircleY = (mHeight) / 2;

其中 mWidth、mHeight 來自 layout_width/layout_height,並取最小值以避免圖像填不滿指定區域。自定義 View 還需對 wrap_content 做特殊處理,否則該屬性的 View 不予顯示。而 mRadius 之所以要減去邊框寬度乘 2,是為了給邊框騰出空間——若圓恰為視圖的內切圓,邊框就會被畫到視圖外而看不全。

接著繪製邊框,只需再定義一個 Paint 畫一個圓:

 mBorderPaint = new Paint(); mBorderPaint.setStyle(Paint.Style.STROKE); mBorderPaint.setStrokeWidth(mBorderWidth); mBorderPaint.setColor(mBorderColor); mBorderPaint.setStrokeCap(Paint.Cap.ROUND);

在 onDraw() 中繪製:

 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawCircle(mCircleX, mCircleY, mRadius, mPaint); canvas.drawCircle(mCircleX, mCircleY, mRadius, mBorderPaint); }

使用方式:

 <com.example.hwaphon.patheffecttest.MyView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="16dp" android:layout_marginRight="8dp" app:mborder_color="@android:color/holo_green_light" app:mborder_width="4dp" app:msrc="@drawable/myview_test"/>

別忘了在容器中加上 xmlns:app=https://schemas.android.com/apk/res-auto。

以上就是利用 BitmapShader 製作自帶邊框圓形頭像的全部內容,希望對大家開發 Android 時有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved