6

Is there any simple way how to draw obliquely strike through on TextView? Now I'm using this code:

textview.setPaintFlags(textview.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);

But I need something like this:
enter image description here
I'm not very familiar with Paint API how to simply achive this so any help will be appreciated.
Thank you.

Warlock
  • 2,481
  • 4
  • 31
  • 45
  • Hello read this http://stackoverflow.com/questions/3881553/is-there-an-easy-way-to-strike-through-text-in-an-app-widget – Raghav Jun 26 '12 at 16:45
  • I saw that post, but I need it obliquely. I tried using 9patch before, but the outcome looks ugly. – Warlock Jun 26 '12 at 17:06

1 Answers1

11

It's pretty easy with a custom TextView class. Check out the Canvas guide from the documentation for more info on this. Note the comments where you can change the color/width:

public class ObliqueStrikeTextView extends TextView
{
    private int dividerColor;
    private Paint paint;

    public ObliqueStrikeTextView(Context context)
    {
        super(context);
        init(context);
    }

    public ObliqueStrikeTextView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init(context);
    }

    public ObliqueStrikeTextView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context)
    {
        Resources resources = context.getResources();
        //replace with your color
        dividerColor = resources.getColor(R.color.black);

        paint = new Paint();
        paint.setColor(dividerColor);
        //replace with your desired width
        paint.setStrokeWidth(resources.getDimension(R.dimen.vertical_divider_width));
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        canvas.drawLine(0, getHeight(), getWidth(), 0, paint);
    }
}

You can use it in a layout file by fully qualifying the view with your package, like this:

<your.package.name.ObliqueStrikeTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1234567890"
        android:textSize="20sp"/>

Here's the end result:

Screenshot

wsanville
  • 37,158
  • 8
  • 76
  • 101
  • Exactly what I was looking for. I just add some "anti-analising" to make it look better. Thanks! – Warlock Jun 27 '12 at 17:05
  • Have a look at this answer for non-static strike through width. https://stackoverflow.com/a/51890541/3541465 – Aakash Aug 17 '18 at 07:42