編輯:關於 Android 程式設計
效果如下:

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 時有所幫助。
搞懂 Android 多 DPI 下 drawable 與 values 資源的加載順序
做個簡單的記錄。Google 搞出了一整套 dip、sp、mdpi、hdpi、xhdpi 之類的單位與密度概念,簡單來說,就是為了讓我們能輕鬆實現「與設備密度無關的視覺大
用 Espresso、Mockito 與 Dagger 2 打造快速可靠的 Android UI 測試
前言 Iván Carballo 與他的團隊寫了大約 250 個 UI 測試,跑完只要三分鐘。這篇整理他們的做法:如何用 Mockito 與 Dagger 2 把 UI
基於 Android ListView 的加載提示實現技巧
程序員很多,高手也很多,但真正懂設計的程序員並不多。我覺得我們不僅要成為一個 coder,還要努力成為一個 designer。 我是一個比較注重用戶體驗(UED)的人。對
自訂 ScrollView 實作背景圖片伸縮動效:完整思路與程式碼
用過多米音樂的朋友都知道,它的某個 UI 可以上下滑動——作用嘛,無聊時可以劃劃解解悶。這種細節往往被形容成一種「情懷」,不過叫「情味」或許更貼切。如今行動網際網路發