LoginSignup
9
0

More than 1 year has passed since last update.

5分で出来るCompose風画像編集機能

Posted at

Androidで、できるだけ簡単に画像編集機能を作成したい。
できればUIは自分で弄りたい。
更にできればUIはXMLではなく、Composeで作成したい。

という方法をこれから説明致します。

まず、画像編集機能はこちらのライブラリを利用します。
https://github.com/burhanrashid52/PhotoEditor

PhotoEditorでは画像編集機能を持ったViewを提供してくれて、
描く、文字表示、消しゴム、フィルターといった機能が実現できます。
PhotoEditorの良いところは機能のみを提供してくれてそれを実現するUIは利用側が好きに作ることができるところです。

PhotoEditorを使用する方法をざっくり説明すると、
PhotoEditorViewという専用のViewをXMLレイアウトにセットして
PhotoEditorViewとContextからPhotoEditorを作成します。
そのPhotoEditorに対して設定を行うことで描く、文字表示、消しゴム、フィルターといった機能を利用できます。

Jetpack Composeにはご存知、既存のXMLリソースをComposeUIで利用するための仕組みがあります。それがAndroidViewコンポーザブルです。(詳細は下記URLをご参照ください)
https://developer.android.com/jetpack/compose/interop/interop-apis?hl=ja#views-in-compose

というわけど、AndroidVeiwコンポーザブルにPhotoEditorViewをガッチャンコ。

まずはgradleに以下のライブリを追加。

    implementation 'com.burhanrashid52:photoeditor:2.0.0'
    // 以下はAndroidVeiwコンポーザブルにガッチャンコするのに必要
    implementation "androidx.constraintlayout:constraintlayout-compose:1.0.1"
    implementation "androidx.compose.ui:ui-viewbinding:1.3.2"

あとはよしなにAndroidViewを呼び出します。

    var photoEditor by remember { mutableStateOf<PhotoEditor?>(null) }
    AndroidView(
        modifier = Modifier.height(480.dp).fillMaxWidth(),
        factory = { context ->
            val editorView = PhotoEditorView(context)
            editorView.source.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.tower))  
            editorView
        },
        update = { editorView ->
            photoEditor = PhotoEditor.Builder(editorView.context, editorView)
                .setPinchTextScalable(true)
                .setClipSourceImage(true)
                .build()
        }
    )

    // とりあえずブラシモードを利用できるようにします。
    photoEditor?.setBrushDrawingMode(true)
    val brushSize = 250f
    val opacitySize = 125
    val color = 0xffff0000.toInt()

    val builder = ShapeBuilder()
        .withShapeOpacity(opacitySize)
        .withShapeColor(color)
        .withShapeSize(brushSize)

    photoEditor?.setShape(builder)

完成動画

これで画像編集機能を無事使えるようになりました!!!
やったね☆

PhotoEditorのちょっと気になるところ

上のサンプルコードで

    val brushSize = 250f
    val opacitySize = 125
    val color = 0xffff0000.toInt()

ブラシの透過率を
opacitySizeで設定しているんですが、これのMAXは255なんですね。
なら描画されるのは半透明の赤では??と思われるかもしれないのですが、PhotoEditor 2.0.0ではバグのために透過されません。(一応PRは出しました)
透過率を設定したい場合はフォークして修正して使う必要がありそうです。

以上です!

9
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
0