TextView-shadow 阴影实现

直接上代码

1)实现普通效果

 <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:shadowColor="#ff0000"
        android:shadowDx="3"
        android:shadowDy="3"
        android:shadowRadius="1"
        android:text="abcdefg"
        android:textColor="#0000ff"
        android:textSize="100sp" />

运行结果如下

2)测试下各个属性值影响

1.

android:shadowRadius="0"

结果


所以,只要让
shadowRadius = 0,就不会有阴影显示

2.
android:shadowRadius="20"

结果

它控制的主要就是阴影的宽度,它的值也大,阴影越大,而且颜色越淡

3.测试下dx,dy的作用

        android:shadowDx="30"
        android:shadowDy="30"

结果

也就是阴影的偏移量。

总结如下

1. android:shadowColor:阴影的颜色

2. android:shadowDx:水平方向上的偏移量

3. android:shadowDy:垂直方向上的偏移量

4. android:shadowRadius:是阴影的的半径大小

以上变量全是px单位。而且,如果您想用@dimen引用,会报错。

如果你想在代码中使用,可以使用如下方法

package com.example.imagetest;

import android.R.integer;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {
    TextView tv;
    Button bt;
    int a;
    float t1;
    float t2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.tv);
        bt = (Button) findViewById(R.id.bt);
        a = 0;
        t1 = getResources().getDimension(R.dimen.activity_horizontal_margin);
        t2 = getResources().getDimension(R.dimen.activity_vertical_margin);

        bt.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (a == 1) {
                    // R.color没有效果
                    tv.setShadowLayer(t1, t1, t1, R.color.aaa);
                    a = 0;

                } else {
                    tv.setShadowLayer(t2, t2, t2, 0x800000ff);
                    a = 1;
                }
                bt.setText(a + "");
            }
        });

    }
    
    
}

也就是setShadowLayer方法

setShadowLayer(radius, dx, dy, color);

它的四个参数,分别对应上面的四个属性

四个属性取值,要么直接写,要么使用getResource进行一步转化才行

原文地址:https://www.cnblogs.com/zhangshuli-1989/p/zhangshuli_shadow_150424131.html