Sunday, January 18, 2015

android custom textview with round stroke drawing

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint.Join;
import android.graphics.Paint.Style;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.widget.TextView;

import com.hiimeloyun.android.R;

/**
 *
 * @author boroo
 */
public class StrokeTextView extends TextView {

    private final int strokeColor;
    private final float strokeWidth;

    TextPaint paint = new TextPaint();

    public StrokeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.StrokeStyleable, 0, 0);
        strokeWidth = a.getDimension(R.styleable.StrokeStyleable_strokeWidth, 10);
        strokeColor = a.getColor(R.styleable.StrokeStyleable_strokeColor, Color.BLACK);
    }

    // overridden methods
    @Override
    protected void onDraw(Canvas canvas) {
        final ColorStateList textColor = getTextColors();
      
        paint = this.getPaint();

        paint.setStyle(Style.STROKE);
        paint.setStrokeJoin(Join.ROUND);
        paint.setStrokeMiter(10);
        this.setTextColor(strokeColor);
        paint.setStrokeWidth(strokeWidth);

        super.onDraw(canvas);
        paint.setStyle(Style.FILL);

        setTextColor(textColor);
        super.onDraw(canvas);
    }
}

No comments: