0
0

背景にぼかし(Blur)をかける

Posted at

やること

image2.png

こんな感じで背景画像にぼかしをかけてエモい感じにしたい

やり方

RenderEffect.createBlurEffectを使用する

実装例

・activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    
<!--背景にする画像を貼り付けるImageView-->
    <ImageView
        android:id="@+id/back_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:scrollX="80dp"
        android:src="@drawable/back" />

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragmentContainerView"
        android:name="jp.com.mycomp_module_a.StartFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

・MainActivity.kt

class MainActivity : AppCompatActivity() {
private lateinit var b: ActivityMainBinding
    @RequiresApi(Build.VERSION_CODES.S)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.apply {
            statusBarColor = Color.TRANSPARENT
            setDecorFitsSystemWindows(false)
        }
        b = ActivityMainBinding.inflate(layoutInflater)
        setContentView(b.root)
        b.apply {
            //ImageViewにぼかし(Blur)を設定        
            backImage.setRenderEffect(RenderEffect.createBlurEffect(30f,30f,Shader.TileMode.MIRROR))
        }
    }
}

注意
RenderEffectを使用するには、APIレベル31以上が必要

・直接root要素のレイアウトにエフェクトをかけると、そのレイアウトに所属する全てのViewにぼかしがかるので、背景画像用のImageViewだけに適用する

まとめ

・背景画像にぼかしをかけるにはRenderEffect.createBlurEffectを使用する
・全体にぼかしがかからないよう、背景画像用のImageViewを用意する

・RenderEffectを使うと他にも色々できそう

0
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
0
0