-
[ImageView] ScaleType: Matrix (예제)Software/Android : 안드로이드 2018. 8. 20. 23:41반응형
예제:
이제 실제 코드를 통해서 Matrix의 Scalling, Rotation, Translation 등을 살펴보도록 하자. 예제에 앞서 일반적으로 Scaling -> Rotation -> Translation 순으로 연산 한다는 것을 기억하자. 연산의 순서가 달라지면 실제 연산 결과 값이 달라 질수 있기에 연산 순서에 꼭 신경 쓰도록 하자.
- 목표
300 * 200 이미지를 3배로 Scaling하고 90도로 회전 시킨 후 Center crop하여 500 * 500 ImageView에 보이도록 한다.
- scaleType 설정
<ImageView
android:layout_width="500px"
android:layout_height="500px"
android:src="@drawable/sample"
android:background="@color/colorPrimaryDark"
android:scaleType="matrix"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Layout xml에서 ImageView에서 scaleType을 matrix로 설정.
이 경우 ImageView의 사이즈 보다 Image의 사이즈가 작기 때문에 ImageView의 하단에 빈 공간이 발생하게 된다.
- Scalilng
Matrix matrix = imageView.getImageMatrix();
imageView.setImageBitmap(imageBitmap);
float scale = 3f;
matrix.setScale(scale, scale);
이미지의 사이즈를 3배로 늘어나게 되어 900 * 600이 된 상태이기 때문에 이미지의 오른쪽과 하단 부분이 ImageView를 넘어가게 되어 보이지 않게 된다.
- Rotation
Matrix matrix = imageView.getImageMatrix();
imageView.setImageBitmap(imageBitmap);
float scale = 3f;
matrix.setScale(scale, scale);
int degree = 90;
matrix.postRotate(degree);
90도로 회전 시키게 되면 이미지가 ImageView의 영역 밖으로 나가 버리게 되어 아무것도 보이지 않게 된다.
- Translate
Rotate 이 후 해당 이미지가 ImageView의 중앙에 위치할 수 있도록 이동을 시켜주어야 한다.
Degree 90의 값으로 Rotate된 경우 현재 이미지가 ImageView의 좌측에 위치하고 있기 때문에 먼저 Bitmap의 width 만큼 우측 이동을 시켜주어야 한다. 이 후 ImageView의 center X 값에 이미지의 center X 값을 빼주면 된다. 그리고 y 값의 경우는 ImageView의 center Y 값에 이미지의 center Y의 값을 뺀 만큼 이동 시켜주면 된다. 이를 수식화 하면 아래와 같다.
- 참고: 아래 수식의 경우 Degree 90으로 Rotate 연산이 이루어 진 경우에 대한 이동 계산식으로 상황에 따라 적절한 이동 계산식을 세워야 한다.
dx = RotatedWidth * scale + ImageView.getWidth / 2 - RotatedWidth * scale / 2
= (RotatedWidth * scale - ImageView.getWidth) / 2
dy = (ImageView.getHeight() - RotatedHeight * scale) / 2
int viewWidth = 500;
int viewHeight = 500;
float rotatedWidth = (degree == 90) ? bitmap.getHeight() : bitmap.getWidth();
float rotatedHeight = (degree == 90) ? bitmap.getWidth() : bitmap.getHeight();
float dx = (rotatedWidth * scale - viewWidth) / 2;
float dy = (viewHeight - rotatedHeight * scale) / 2;
matrix.postTranslate(dx, dy);
반응형'Software > Android : 안드로이드' 카테고리의 다른 글
[Java 8] Android Studio 3.x와 Java 8 (0) 2019.03.12 [ImageView] ScaleType: Matrix (행렬) (0) 2018.08.14 댓글