轉(zhuǎn)載請(qǐng)標(biāo)明地址 QuincySx:[http://www.reibang.com/p/71309b2bd0e7]
我們?cè)谧鲰?xiàng)目時(shí)倒庵,往往有一個(gè)這樣的需求:就是對(duì)視圖的一部分進(jìn)行截圖然后分享出去
這個(gè)功能很簡(jiǎn)單還是簡(jiǎn)單的看代碼吧
<android.support.constraint.ConstraintLayout
android:id="@+id/layout_test"
android:layout_width="90dp"
android:layout_height="90dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.3">
<ImageView
android:layout_width="90dp"
android:layout_height="90dp"
android:src="@drawable/icon_image"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="測(cè)試截圖"
android:textColor="#2b24c3"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"/>
</android.support.constraint.ConstraintLayout>
<Button
android:id="@+id/btn_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="點(diǎn)擊測(cè)試"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/layout_test"/>
<ImageView
android:id="@+id/img_show"
android:layout_width="90dp"
android:layout_height="90dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_test"
tools:src="@drawable/icon_image"/>
對(duì) Activity 里面獲取控件的代碼已省略,直接展示業(yè)務(wù)代碼
public void onClick(View view) {
//控件可以進(jìn)行緩存
mConstraintLayout.setDrawingCacheEnabled(true);
//獲取緩存的 Bitmap
Bitmap drawingCache = mConstraintLayout.getDrawingCache();
//對(duì)獲取的 Bitmap 進(jìn)行復(fù)制
drawingCache = drawingCache.createBitmap(drawingCache);
//關(guān)閉視圖的緩存
mConstraintLayout.setDrawingCacheEnabled(false);
if (drawingCache != null) {
mImageView.setImageBitmap(drawingCache);
Toast.makeText(this, "獲取失敗", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "獲取成功", Toast.LENGTH_SHORT).show();
}
}
總結(jié)
看到這個(gè)功能感覺無從下手当船,其實(shí)也挺簡(jiǎn)單的腔丧,如果有需求不妨收藏一下惩阶,分享給有需求的朋友