[Android] XML로부터 View 생성하기

안드로이드는 UI의 구성을 XML로 정의하여 생성한다. 아래는 UI를 위한 XML인 map_legend_item.xml 파일이다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <LinearLayout
        android:paddingHorizontal="15dp"
        android:layout_width="match_parent"
        android:layout_height="54dp"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <Switch
            android:id="@+id/swLayerVisibility"
            android:layout_weight="0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <geoservice.nexgen.maplegend.LegendSingleSymbol
            android:id="@+id/lssItem"
            android:layout_width="36dp"
            android:layout_height="36dp" />

        <Space
            android:layout_width="5dp"
            android:layout_height="1px" />

        <TextView
            android:layout_weight="1"
            android:id="@+id/tvLayerName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="@dimen/normal_text_size"
            android:textStyle="bold"
            android:text="LayerName" />


    </LinearLayout>
</LinearLayout>

위의 XML을 통해 View를 생성하는 코드는 다음과 같다.

for( ... ) {
    val itemLayout = inflater.inflate(R.layout.map_legend_item, null, false)
    itemLayout.findViewById<TextView>(R.id.tvLayerName).setText(title)

    ...

    mainLayout.addView(itemLayout)
}

위의 코드 중 inflater는 다음 3가지 방식 중 하나를 통해 생성된다.

val inflater = layoutInflater
val inflater = LayoutInflater.from(this)
val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

위의 코드를 통한 실제 결과는 다음과 같다.

[Android] 카메라로 찍은 이미지 올바른 방향으로 회전시켜 보여주기

안드로이드의 폰에서 찍은 사진은 내부적으로 카메라의 회전 정보가 담겨 있습니다. 폰으로 찍은 사진을 화면에 표시할때 이 화전 정보를 반영하여 촬영된 이미지를 표시해야 자연스럽습니다. 아래의 코드는 이미지 파일에 대한 회전 정보를 얻는 코드입니다.

val imageFilePath = "...... . jpg"
val ei = ExifInterface(imageFilePath)
val orientation: Int = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)
val angle = when(orientation) {
    ExifInterface.ORIENTATION_ROTATE_90 -> 90f
    ExifInterface.ORIENTATION_ROTATE_180 -> 180f
    ExifInterface.ORIENTATION_ROTATE_270 -> 270f
    else -> 0f
}

위의 코드를 통해 이미지의 회전 각도르 얻어올 수 있고, 이를 토대로 이미지를 실제로 회전시키는 코드는 다음과 같습니다.

private fun resizeBitmap(src: Bitmap, size: Float, angle: Float): Bitmap {
    val width = src.width
    val height = src.height

    var newWidth = 0f
    var newHeight = 0f

    if(width > height) {
        newWidth = size
        newHeight = height.toFloat() * (newWidth / width.toFloat())
    } else {
        newHeight = size
        newWidth = width.toFloat() * (newHeight / height.toFloat())
    }

    val scaleWidth = newWidth.toFloat() / width
    val scaleHeight = newHeight.toFloat() / height

    val matrix = Matrix()

    matrix.postRotate(angle);
    matrix.postScale(scaleWidth, scaleHeight)

    val resizedBitmap = Bitmap.createBitmap(src, 0, 0, width, height, matrix, true)
    return resizedBitmap
}

위의 함수는 카메라로 찍은 이미지를 회전시켜 주는 것뿐만 아니라 이미지의 크기를 화면에 표시하기에 적당한 크기를 인자로 받아 줄여줍니다. 실제 사용하는 코드는 다음과 같습니다.

val imageFilePath = "...... . jpg"
val file = File(imageFilePath)

val angle = ...

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
    val source = ImageDecoder.createSource(contentResolver, Uri.fromFile(file))
    ImageDecoder.decodeBitmap(source)?.let {
        imageView.setImageBitmap(resizeBitmap(it, 900f, 0f))
    }
} else {
    MediaStore.Images.Media.getBitmap(contentResolver, Uri.fromFile(file))?.let {
        imageView.setImageBitmap(resizeBitmap(it, 900f, 0f))
    }
}