1
+ package ta.com.workshop2
2
+
3
+ import android.content.Context
4
+ import android.support.annotation.Nullable
5
+ import android.util.AttributeSet
6
+ import android.view.ViewGroup
7
+ import android.widget.ImageView
8
+
9
+
10
+
11
+ class ImageRatioView : ImageView {
12
+
13
+ var imageOrientation: Int? = 0
14
+ var imageRatio: Int? = 0
15
+
16
+ constructor (context: Context ) : super (context)
17
+
18
+ constructor (context: Context , @Nullable attrs: AttributeSet ) : this (context, attrs, 0 )
19
+
20
+ constructor (context: Context , @Nullable attrs: AttributeSet , defStyleAttr: Int ) : this (context, attrs, defStyleAttr, 0 )
21
+
22
+ constructor (context: Context , @Nullable attrs: AttributeSet , defStyleAttr: Int ,
23
+ defStyleRes: Int ) : super (context, attrs, defStyleAttr, defStyleRes) {
24
+ val a = context.obtainStyledAttributes(attrs, R .styleable.ImageRatioView , defStyleAttr, defStyleRes)
25
+ imageOrientation = a.getInt(R .styleable.ImageRatioView_imageOrientation , 0 )
26
+ imageRatio = a.getInt(R .styleable.ImageRatioView_imageRatio , 0 )
27
+
28
+ a.recycle()
29
+ }
30
+
31
+
32
+ override fun onMeasure (widthMeasureSpec : Int , heightMeasureSpec : Int ) {
33
+
34
+ var width = MeasureSpec .getSize(widthMeasureSpec)
35
+ var height = MeasureSpec .getSize(heightMeasureSpec)
36
+
37
+ when (imageOrientation) {
38
+ 0 -> {
39
+ height = calculateRatio(width)
40
+ }
41
+ 1 -> {
42
+ width = calculateRatio(height)
43
+ }
44
+ }
45
+
46
+ this .setMeasuredDimension(width, height)
47
+ this .layoutParams.width = width
48
+ this .layoutParams.height = height
49
+ super .onMeasure(widthMeasureSpec, heightMeasureSpec)
50
+ }
51
+
52
+
53
+ private fun calculateRatio (measureSpec : Int ) : Int {
54
+ return when (imageRatio) {
55
+ 0 -> measureSpec
56
+ 1 -> measureSpec * (1 / 2 )
57
+ else -> {
58
+ 0
59
+ }
60
+ }
61
+ }
62
+ }
0 commit comments