布局 activity_main.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:ignore="ContentDescription,HardcodedText,UselessParent">
<LinearLayout
android:id="@+id/screenshotLayout"
android:layout_width="310dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginEnd="25dp"
android:layout_marginStart="25dp"
android:layout_marginTop="25dp"
android:background="@drawable/bg_qr_code"
android:orientation="vertical">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="17dp">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:src="@drawable/qq" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_toEndOf="@id/iv_avatar"
android:text="QQ"
android:textColor="#000000"
android:textSize="18sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="@id/tv_name"
android:layout_below="@id/tv_name"
android:text="好友"
android:textColor="#9b9b9b"
android:textSize="14sp" />
</RelativeLayout>
<ImageView
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="24dp"
android:src="@drawable/generate" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="27dp"
android:layout_marginTop="23dp"
android:text="扫一扫加为好友"
android:textColor="#6c6b6e"
android:textSize="12sp"
tools:ignore="HardcodedText" />
</LinearLayout>
</FrameLayout>
执行逻辑
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
screenshotLayout.setOnClickListener { screenShot() }
}
private fun screenShot() {
screenshotLayout.isDrawingCacheEnabled = true
screenshotLayout.buildDrawingCache()
val bitmap = screenshotLayout.getDrawingCache(false) // Bitmap to save.
screenshotLayout.destroyDrawingCache()
screenshotLayout.isDrawingCacheEnabled = false
}
}
截取部分为下图中间卡片