編輯:關於 Android 程式設計
下圖為圓角效果示意:

透過 Bitmap、Canvas 與 PorterDuff 混合模式,可以將圖片的四角處理成圓角。核心思路是:先建立一張與原圖相同尺寸並帶透明通道的輸出圖,用畫布畫出圓角矩形作為遮罩,再以 SRC_IN 模式將原圖合成進去。
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Drawable drawable = getResources().getDrawable(R.drawable.jpg1);
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
Bitmap bitmap = bitmapDrawable.getBitmap();
ImageView imageView = (ImageView) findViewById(R.id.imgShow);
imageView.setImageBitmap(Main.getRoundedCornerBitmap(bitmap));
}
// 將圖片的四角圓化
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
// 得到畫布
Canvas canvas = new Canvas(output);
// 將畫布的四角圓化
final int color = Color.RED;
final Paint paint = new Paint();
// 得到與圖像相同大小的區域,由構造的四個值決定區域的位置以及大小
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
// 值越大角度越明顯
final float roundPx = 50;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
// drawRoundRect 的第 2、3 個參數一樣則畫的是正圓的一角,數值不同則是橢圓的一角
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
}
調整 roundPx 的值即可控制圓角的大小,數值越大圓角越明顯。此方法簡單易用,適合需要為頭像或圖片加上圓角效果的場景。
自製 Canvas 圓餅圖:扇區、引線與標籤自動排版
這篇示範怎麼用 Canvas 手繪一張圓餅統計圖,重點是標籤、引線、百分比全部依扇區大小自動排布,不需要手動調座標。 先看成果: 特點: 1.
Android 仿 iOS 底部彈窗:IOS_Dialog_Library 使用示例
做 Android 開發久了,多少都會嫌系統自帶的 Dialog 樣式單調,和設計稿放在一起總覺得別扭。本文介紹一款開源的仿 iOS 底部彈窗庫 IOS_Dialog_L
Android SwipeRefreshLayout 下拉刷新控件使用方法詳解
如今 Material Design 十分流行,而 SwipeRefreshLayout 就是原生提供的下拉刷新控件(也就是 Facebook 那種效果)。它幾乎可以包裹
Android 事件分發機制淺談:從源碼與 Log 實驗看通透傳、攔截與消費
對剛入門的朋友來說,事件分發往往是個容易被跳過的主題——畢竟只要會寫 setOnClickListener,畫面上就能動起來。但一旦開始自定義 View,特別是處理手勢衝