編輯:關於 Android 程式設計

思路並不複雜:繼承 ImageView,在 onDraw 裡用 Path 畫一個圓並 clipPath,再把 Bitmap 畫進去。
運行效果:

自定義控件:
public class RoundImageView extends ImageView {
private Bitmap mBitmap;
private final Rect mRect = new Rect();
private final PaintFlagsDrawFilter pdf =
new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG);
private final Paint mPaint = new Paint();
private final Path mPath = new Path();
public RoundImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
mPaint.setAntiAlias(true); // 抗鋸齒
}
/** 傳入一個 Bitmap 對象 */
public void setmBitmap(Bitmap bitmap) {
this.mBitmap = bitmap;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mBitmap == null) return;
mRect.set(0, 0, getWidth(), getHeight());
canvas.save();
canvas.setDrawFilter(pdf);
mPath.addCircle(getWidth() / 2f, getHeight() / 2f,
getWidth() / 2f, Path.Direction.CCW);
canvas.clipPath(mPath, Region.Op.REPLACE);
canvas.drawBitmap(mBitmap, null, mRect, mPaint);
canvas.restore();
}
}
Activity 中加載並賦值:
public class MainActivity extends Activity {
private RoundImageView imgRoundImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
imgRoundImageView = (RoundImageView) findViewById(R.id.img_round);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bulunou);
imgRoundImageView.setmBitmap(bitmap);
}
}
布局中直接使用全限定類名即可:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android_drawable_xml.MainActivity">
<com.example.android_drawable_xml.RoundImageView
android:id="@+id/img_round"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_gravity="center"
android:layout_margin="5px" />
</LinearLayout>

這就是 QQ 設置頭像時的裁剪界面,本質上就是一次 ImageView 的裁剪與顯示。
運行結果:

做得比較粗糙,你可以在這個基礎上繼續打磨。核心代碼:
public class CutImageView extends Activity implements OnClickListener {
private Button selectImageBtn;
private Button cutImageBtn;
private ImageView imageView;
private static final int IMAGE_SELECT = 1; // 選擇圖片
private static final int IMAGE_CUT = 2; // 裁剪圖片
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cut_imageview);
selectImageBtn = (Button) findViewById(R.id.selectImgBtn);
cutImageBtn = (Button) findViewById(R.id.cutImageBtn);
imageView = (ImageView) findViewById(R.id.imageview3);
selectImageBtn.setOnClickListener(this);
cutImageBtn.setOnClickListener(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) return;
if (requestCode == IMAGE_SELECT) {
Uri uri = data.getData(); // 圖片路徑
int dw = getWindowManager().getDefaultDisplay().getWidth(); // 屏幕寬
int dh = getWindowManager().getDefaultDisplay().getHeight() / 2;
try {
// 先只讀邊界信息,避免大圖直接撐爆內存
BitmapFactory.Options factory = new BitmapFactory.Options();
factory.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, factory);
int hRatio = (int) Math.ceil(factory.outHeight / (float) dh);
int wRatio = (int) Math.ceil(factory.outWidth / (float) dw);
// 縮小到 1/ratio 的尺寸與 1/ratio^2 的像素量
if (hRatio > 1 || wRatio > 1) {
factory.inSampleSize = (hRatio > wRatio) ? hRatio : wRatio;
}
factory.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory.decodeStream(
getContentResolver().openInputStream(uri), null, factory);
imageView.setImageBitmap(bmp);
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == IMAGE_CUT) {
Bitmap bitmap = data.getParcelableExtra("data");
imageView.setImageBitmap(bitmap);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.selectImgBtn:
// 打開系統圖庫
startActivityForResult(new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI), IMAGE_SELECT);
break;
case R.id.cutImageBtn:
startActivityForResult(getImageClipIntent(), IMAGE_CUT);
break;
}
}
private Intent getImageClipIntent() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*"); // 任意圖片類型
intent.putExtra("crop", "true"); // 開啟裁剪
intent.putExtra("aspectX", 1); // 裁剪框比例 1:1
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 80); // 輸出圖片尺寸
intent.putExtra("outputY", 80);
intent.putExtra("return-data", true);
return intent;
}
}
關鍵點是 inJustDecodeBounds = true:先只讀取圖片的寬高邊界而不真正分配像素內存,算出合適的 inSampleSize 之後再正式解碼,這是加載大圖必備的減壓手法。
最簡單的縮放方式是改變 ImageView 的尺寸,把 android:scaleType 設為 fitCenter 即可。若需要旋轉,則可以借助 android.graphics.Matrix 的 setRotate 方法。
下面用兩個 SeekBar 分別控制尺寸與角度:
運行效果:

public class ImageViewRotateText extends Activity implements OnSeekBarChangeListener {
private final int minWidth = 80;
private ImageView imageView;
private TextView textView1, textView2;
private final Matrix matrix = new Matrix();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rotate_imageview);
imageView = (ImageView) findViewById(R.id.imageview5);
SeekBar seekBar1 = (SeekBar) findViewById(R.id.seekbar1);
SeekBar seekBar2 = (SeekBar) findViewById(R.id.seekbar2);
textView1 = (TextView) findViewById(R.id.textview1);
textView2 = (TextView) findViewById(R.id.textview2);
seekBar1.setOnSeekBarChangeListener(this);
seekBar2.setOnSeekBarChangeListener(this);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
seekBar1.setMax(dm.widthPixels - minWidth);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (seekBar.getId() == R.id.seekbar1) {
int newWidth = progress + minWidth;
int newHeight = (int) (newWidth * 3 / 4f); // 按原圖比例縮放
imageView.setLayoutParams(new LinearLayout.LayoutParams(newWidth, newHeight));
textView1.setText("圖像寬度: " + newWidth + " 圖像高度: " + newHeight);
} else if (seekBar.getId() == R.id.seekbar2) {
Bitmap bitmap = ((BitmapDrawable) getResources()
.getDrawable(R.drawable.xingkong)).getBitmap();
matrix.setRotate(progress); // 設置旋轉角度
bitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
imageView.setImageBitmap(bitmap);
textView2.setText(progress + "度");
}
}
@Override public void onStartTrackingTouch(SeekBar seekBar) { }
@Override public void onStopTrackingTouch(SeekBar seekBar) { }
}
運行效果:

布局:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="下載網絡圖片" />
</LinearLayout>
Activity:
public class Main extends Activity {
private Button button;
private ImageView imageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button);
imageView = (ImageView) findViewById(R.id.imageview);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
byte[] data = HttpUtils.getImageViewArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
imageView.setImageBitmap(bitmap);
}
});
}
}
網絡工具類,同時提供「返回流」與「返回字節數組」兩種取圖方式:
public class HttpUtils {
private static final String URL_PATH =
"https://img.my.csdn.net/uploads/201202/8/0_13287131646nNZ.gif";
/** 以流的形式返回圖片 */
public static InputStream getImageViewInputStream() throws IOException {
InputStream inputStream = null;
URL url = new URL(URL_PATH);
if (url != null) {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
if (conn.getResponseCode() == 200) {
inputStream = conn.getInputStream();
}
}
return inputStream;
}
/** 以字節數組的形式返回圖片 */
public static byte[] getImageViewArray() {
byte[] data = null;
InputStream inputStream = null;
// 直接寫進內存,省去文件輸出流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
URL url = new URL(URL_PATH);
if (url != null) {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
int len;
byte[] buffer = new byte[1024];
if (conn.getResponseCode() == 200) {
inputStream = conn.getInputStream();
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
data = outputStream.toByteArray();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); }
}
}
return data;
}
}
有不清楚的地方記得多查多問。<完>
有話微笑說是什麼 網絡電話怎麼打
「有話微笑說」聽名字就頗為新鮮。這款App之所以受歡迎,正是因為通話品質穩定、資費便宜,長期用下來能省下不少話費。它究竟是什麼?又該怎麼打電話?小編下面就說清楚。 有話微
一次搞懂 Android 介面適配:從單位換算到 .9 圖的實戰筆記
為什麼 Android 一定要談適配 答案很直接:碎片化。海外統計機構 OpenSignal 曾公布過多份裝置調查,把去年 8 月的數據攤開來看會更清楚——裝置型號多、品
Android Studio 2.0 搭建 NDK 環境並成功編譯 so 文件
在 Android 開發中,NDK 應用場景越來越常見,例如游戲引擎、音視頻處理、性能優化等。本文將以 Android Studio 2.0 為例,介紹如何搭建 NDK
用 WebView 做一個簡易瀏覽器:返回、前進、首頁與網址輸入實作
WebView 是 Android 中非常實用的元件,與 Safari、Chrome 同樣基於 WebKit 渲染引擎,能直接載入 HTML 來呈現介面。本文示範如何用它