Add opaque “shadow” (outline) to Android TextView

前端 未结 3 1882
借酒劲吻你
借酒劲吻你 2020-12-03 08:08

I have a TextView in my Activity to which I want to add a shadow. It is supposed to look like in OsmAnd (100% opaque):

But it looks like this:

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 09:02

    I tried all the hacks, tips and tricks in the other posts like here, here and here.

    None of them works that great or looks so good.

    Now this is how you really do it (found in the Source of the OsmAnd app):

    You use a FrameLayout (which has the characteristic of laying its components over each other) and put 2 TextViews inside at the same position.

    MainActivity.xml:

    
    
    
        
    
            
    
            
        
    
    
    

    And in the onCreate method of your activity you set the stroke width of the shadow TextView and change it from FILL to STROKE:

    import android.graphics.Paint;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.TextView;
        
    public class MainActivity extends AppCompatActivity {    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        
            //here comes the magic
            TextView textViewShadow = (TextView) findViewById(R.id.textViewShadowId);
            textViewShadow.getPaint().setStrokeWidth(5);
            textViewShadow.getPaint().setStyle(Paint.Style.STROKE);
        }
    }
    

    The result looks like this:

提交回复
热议问题