Android View — Paint 详解

Android View — Paint 详解

在Android View 的概念中,Paint 如名字所代表的含义,是画笔的意思。像我们平时画图一样,Paint就是相当于笔,而Canvas就是纸,这里叫画布。Paint 可以设置的多种属性。

PaintCanvasView

定义一个最简单的自定义View来展示Paint 的多种属性。

  1. 重写onDraw 方法,在onDrasw 方法中调用子类的onChildDraw 方法,
  2. 所有的子类都要事先抽象的onChildDraw 方法,在onChildDraw真正的绘制图形
  3. onSizeChanged 确定View的宽和高。作为绘制View的宽和高的依据。
public abstract class PaintCanvasView extends View {
    protected Paint mPaint = new Paint();
    protected int mWidth;
    protected int mHeigth;
    protected RectF mRectF;

    public PaintCanvasView(Context context) {
        super(context);
        mRectF = new RectF();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        onChildDraw(canvas);
    }

    protected abstract void onChildDraw(Canvas canvas);

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = w;
        mHeigth = h;

        mRectF.left = 0;
        mRectF.top = 0;
        mRectF.right = w;
        mRectF.bottom = h;
    }


绘制文字

Paint 最基本的功能就是绘制文字。基本属性有:

  1. setTextSize 设置文字的大小
  2. setColor 设置文字的颜色
  3. setTextScaleX 水平方向上的缩放
  4. setTextSkewX 水平方向上的倾斜度
  5. setTypeface(Typeface typeface) 设置字体
paint_text.png
    static public class TextPaintCanvasView extends PaintCanvasView{

        public TextPaintCanvasView(Context context) {
            super(context);
        }

        @Override
        protected void onChildDraw(Canvas canvas) {
            mPaint.setTextSize(mWidth/20);
            mPaint.setColor(Color.BLUE);
            mPaint.setTypeface(Typeface.SERIF);
            canvas.drawText("View Hello World", mWidth/10, mHeigth*1/4, mPaint);

            mPaint.setTextScaleX(2);
            canvas.drawText("View Hello World", mWidth/10, mHeigth*2/4, mPaint);

            mPaint.setTextScaleX(1);
            mPaint.setTextSkewX(-1);
            canvas.drawText("View Hello World", mWidth/10, mHeigth*3/4, mPaint);
        }
    }

setShadowLayer

绘制文字的阴影

/**
 * This draws a shadow layer below the main layer, with the specified
 * offset and color, and blur radius. If radius is 0, then the shadow
 * layer is removed.
 * <p>
 * Can be used to create a blurred shadow underneath text. Support for use
 * with other drawing operations is constrained to the software rendering
 * pipeline.
 * <p>
 * The alpha of the shadow will be the paint's alpha if the shadow color is
 * opaque, or the alpha from the shadow color if not.
 */
public void setShadowLayer(float radius, float dx, float dy, int shadowColor);
paint_shadowLayer.png
    public static class ShadowLayerPaintView extends PaintCanvasView {
        public ShadowLayerPaintView(Context context) {
            super(context);
        }

        @Override
        protected void onChildDraw(Canvas canvas) {
            mPaint.setTextSize(mWidth/10);
            mPaint.setColor(Color.BLUE);
            mPaint.setShadowLayer(20, 0, 20, Color.GREEN);
            canvas.drawText("View Hello World", mWidth/10, mHeigth/2, mPaint);
        }
    }

setStrokeWidth

设置描边的宽度,在绘制 线条,各种几何图形时使用。
需要配合设置 style is Stroke or StrokeAndFill

paint_StrokeWidth.png
    static public class LinePaintCanvasView extends PaintCanvasView{

        public LinePaintCanvasView(Context context) {
            super(context);
        }

        @Override
        protected void onChildDraw(Canvas canvas) {
            mPaint.setColor(Color.BLUE);
            mPaint.setStrokeWidth(10);
            canvas.drawLine(mWidth/10, mHeigth/2, mWidth - mWidth/10, mHeigth/2, mPaint);
        }
    }

Cap

Cap 表示表示画笔在离开画板时候留下的最后一点图形,比如矩形,圆形等。有三种:

  1. BUTT 正常模式
  2. ROUND
  3. SQUARE
  4. 默认是BUTT, 但是从图上可以看出设置与不设置在长度上有一些差异。
paint_cap.png
 public enum Cap {
        BUTT    (0),
        ROUND   (1),
        SQUARE  (2);
    }
    static public class CapPaintCanvasView extends PaintCanvasView{

        @Override
        protected void onChildDraw(Canvas canvas) {

            mPaint.setColor(Color.DKGRAY);
            mPaint.setStrokeWidth(50);
            canvas.drawLine(mWidth/10, mHeigth/5, mWidth - mWidth/10, mHeigth/5, mPaint);

            mPaint.setStrokeCap(Paint.Cap.BUTT);
            canvas.drawLine(mWidth/10, mHeigth*2/5, mWidth - mWidth/10, mHeigth*2/5, mPaint);

            mPaint.setStrokeCap(Paint.Cap.ROUND);
            canvas.drawLine(mWidth/10, mHeigth*3/5, mWidth - mWidth/10, mHeigth*3/5, mPaint);

            mPaint.setStrokeCap(Paint.Cap.SQUARE);
            canvas.drawLine(mWidth/10, mHeigth*4/5, mWidth - mWidth/10, mHeigth*4/5, mPaint);
        }
    }

Jonin

Jonin 表示图形连接处的样式.有锐角,圆形,斜面三种。

    public enum Join {
        MITER   (0),
        ROUND   (1),
        BEVEL   (2);
    }
paint_join.png
static public class JoinPaintCanvasView extends PaintCanvasView{

        @Override
        protected void onChildDraw(Canvas canvas) {

            mPaint.setColor(Color.CYAN);
            mPaint.setStrokeWidth(50);
            mPaint.setStyle(Paint.Style.STROKE);

            Path  path = new Path();
            path.moveTo(mWidth/8, mHeigth/10);
            path.lineTo(mWidth/4, mHeigth - mHeigth/8);

            mPaint.setStrokeJoin(Paint.Join.MITER);
            path.lineTo(mWidth/2, mHeigth/8);
            canvas.drawPath(path, mPaint);

            mPaint.setStrokeJoin(Paint.Join.ROUND);
            path.lineTo(mWidth*3/4, mHeigth - mHeigth/8);
            canvas.drawPath(path, mPaint);

            mPaint.setStrokeJoin(Paint.Join.BEVEL);
            path.lineTo(mWidth*7/8, mHeigth/8);
            canvas.drawPath(path, mPaint);
        }
    }

Align

Align 用于在绘制文本时表示的对齐方式:

    public enum Align {
        LEFT    (0),
        CENTER  (1),
        RIGHT   (2);
    }
paint_align.png
    static public class AlignPaintCanvasView extends PaintCanvasView{

        @Override
        protected void onChildDraw(Canvas canvas) {

            mPaint.setTextSize(mWidth/10);
            mPaint.setColor(Color.BLUE);
            mPaint.setTextAlign(Paint.Align.LEFT);
            canvas.drawText("Align View", mWidth/2, mHeigth*1/4, mPaint);

            mPaint.setTextAlign(Paint.Align.CENTER);
            canvas.drawText("Align View", mWidth/2, mHeigth*2/4, mPaint);

            mPaint.setTextAlign(Paint.Align.RIGHT);
            canvas.drawText("Align View", mWidth/2, mHeigth*3/4, mPaint);
        }
    }

ColorFilter

ColorMatrixColorFilter

颜色ColorMatrix 是一个5*4的矩阵. 默认的ColorMatrix为:【
1, 0, 0, 0, 0, // R
0, 1, 0, 0, 0, // G
0, 0, 1, 0, 0, // B
0, 0, 0, 1, 0, // A

最后一列表示偏移。通过函数
public void setScale(float rScale, float gScale, float bScale,float aScale) 来控制各个颜色分量的比重。

paint_ColorMatrix.png
/**
 * 4x5 matrix for transforming the color and alpha components of a Bitmap.
 * The matrix can be passed as single array, and is treated as follows:
 *
 *  [ a, b, c, d, e,
 *    f, g, h, i, j,
 *    k, l, m, n, o,
 *    p, q, r, s, t ]
 *
 * When applied to a color [R, G, B, A] the resulting color
 * is computed as:
 *   R = a*R + b*G + c*B + d*A + e;
 *   G = f*R + g*G + h*B + i*A + j;
 *   B = k*R + l*G + m*B + n*A + o;
 *   A = p*R + q*G + r*B + s*A + t;
 *   
    static public class ColorMatrixColorFilterView extends PaintCanvasView{

        @Override
        protected void onChildDraw(Canvas canvas) {

            ColorMatrix colorMatrix = new ColorMatrix(new float[]{
                    1, 0, 0, 0, 0,
                    0, 1, 0, 0, 0,
                    0, 0, 1, 0, 0,
                    0, 0, 0, 1, 0,
            });

            int strokeWidth = 20;
            int min = Math.min(mWidth, mHeigth);
            int radius = min/3;

            mPaint.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
            mPaint.setColor(Color.argb(255, 255, 128, 103));
            canvas.drawCircle(mRectF.centerX(), mRectF.centerY(), min/2, mPaint);

            colorMatrix.setScale(0, 1f, 1f, 1f);
            mPaint.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
            canvas.drawCircle(mWidth/3/2,   mHeigth/2, radius - strokeWidth, mPaint);

            mPaint.setColor(Color.argb(255, 255, 128, 103));
            colorMatrix.setScale(1, 0f, 0f, 1f);
            mPaint.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
            canvas.drawCircle(mWidth*5/6, mHeigth/2, radius - strokeWidth, mPaint);
        }
    }

LightingColorFilter

LightingColorFilter 和 ColorMatrixColorFilter 道理上上一样的,都是通过控制RGBA 的数值实现滤镜的效果。在参数上有一些差异,ColorMatrixColorFilter 是分别操作颜色的各个通道。LightingColorFilter 则是直接传入两个RGBA的色彩参数。

paint_LightingColorFilter.png
/**
 *
 * Given a source color RGB, the resulting R'G'B' color is computed thusly:
 * R' = R * colorMultiply.R + colorAdd.R
 * G' = G * colorMultiply.G + colorAdd.G
 * B' = B * colorMultiply.B + colorAdd.B
 */
 
    static public class LightingColorFilterView extends PaintCanvasView{
        Context mContext;
        public LightingColorFilterView(Context context) {
            super(context);
            mContext = context;
            setLayerType(LAYER_TYPE_SOFTWARE, null);
        }

        @Override
        protected void onChildDraw(Canvas canvas) {
            Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.colorfilter);
            Rect srcRect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
            int min = Math.min(mWidth, mHeigth)/3;

            canvas.drawBitmap(bitmap, srcRect, new Rect(mWidth/2 - min, mHeigth/2 - min, mWidth/2 + min, mHeigth/2 + min), mPaint);
            mPaint.setColorFilter(new LightingColorFilter(0xFF00FFFF, 0x00FF0000));
            canvas.drawBitmap(bitmap, srcRect, new Rect(mWidth/6 - min, mHeigth/2 - min, mWidth/6 + min, mHeigth/2 + min), mPaint);
            mPaint.setColorFilter(new LightingColorFilter(0xFF00FFFF, 0x00000000));
            canvas.drawBitmap(bitmap, srcRect, new Rect(mWidth*5/6 - min, mHeigth/2 - min, mWidth*5/6 + min, mHeigth/2 + min), mPaint);
        }
    }

PorterDuffColorFilter

PorterDuffColorFilter 构造参数需要传入两个参数。第一个为颜色值,第二个为混合模式。
然后Paint 在draw Bitmap 的时候Bitmap 和颜色值 按照第二个参数的进行混合。

paint_PorterDuffColorFilter.png
    static public class PorterDuffColorFilterView extends PaintCanvasView{
        Context mContext;

        public PorterDuffColorFilterView(Context context) {
            super(context);
            mContext = context;
            setLayerType(LAYER_TYPE_SOFTWARE, null);
        }

        @Override
        protected void onChildDraw(Canvas canvas) {
            Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.androidicon);
            Rect srcRect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
            int min = Math.min(mWidth, mHeigth)/3;

            canvas.drawBitmap(bitmap, srcRect, new Rect(mWidth/2 - min, mHeigth/2 - min, mWidth/2 + min, mHeigth/2 + min), mPaint);

            mPaint.setColorFilter(new PorterDuffColorFilter(Color.DKGRAY, PorterDuff.Mode.DST));
            canvas.drawBitmap(bitmap, srcRect, new Rect(mWidth/6 - min, mHeigth/2 - min, mWidth/6 + min, mHeigth/2 + min), mPaint);

            mPaint.setColorFilter(new PorterDuffColorFilter( Color.argb(255, 255, 128, 103), PorterDuff.Mode.SRC));
            canvas.drawBitmap(bitmap, srcRect, new Rect(mWidth*5/6 - min, mHeigth/2 - min, mWidth*5/6 + min, mHeigth/2 + min), mPaint);
        }
    }

MaskFilter

BlurMaskFilterView

BlurMaskFilter为模糊面罩,可以在图形边缘添加一些毛玻璃效果。
BlurMaskFilter 构造函数两个参数,第一个参数为阴影的模糊半径,第二个参数为模糊模式 枚举类型 Blur。

public BlurMaskFilter(float radius, Blur style)

这个API不支持硬件加速,需要设置:

setLayerType(LAYER_TYPE_SOFTWARE, null);

public enum Blur {
        /**
         * Blur inside and outside the original border.
         */
        NORMAL(0),
        
        /**
         * Draw solid inside the border, blur outside.
         */
        SOLID(1),

        /**
         * Draw nothing inside the border, blur outside.
         */
        OUTER(2),

        /**
         * Blur inside the border, draw nothing outside.
         */
        INNER(3);
        
        Blur(int value) {
            native_int = value;
        }
        final int native_int;
    }
paint_BlurMaskFilter.png
    static public class BlurMaskFilterView extends PaintCanvasView{

        @Override
        protected void onChildDraw(Canvas canvas) {

            int strokeWidth = 20;
            int min = Math.min(mWidth, mHeigth);
            int radius = mWidth/8;
            mPaint.setStrokeWidth(strokeWidth);
            mPaint.setColor(Color.RED);

            mPaint.setMaskFilter(new BlurMaskFilter(strokeWidth, BlurMaskFilter.Blur.NORMAL));
            canvas.drawCircle(mWidth/4/2,   mHeigth/2, radius - strokeWidth, mPaint);

            mPaint.setMaskFilter(new BlurMaskFilter(strokeWidth, BlurMaskFilter.Blur.SOLID));
            canvas.drawCircle(mWidth*3/4/2, mHeigth/2, radius - strokeWidth, mPaint);

            mPaint.setMaskFilter(new BlurMaskFilter(strokeWidth, BlurMaskFilter.Blur.OUTER));
            canvas.drawCircle(mWidth*5/4/2, mHeigth/2, radius - strokeWidth, mPaint);

            mPaint.setMaskFilter(new BlurMaskFilter(strokeWidth, BlurMaskFilter.Blur.INNER));
            canvas.drawCircle(mWidth*7/8, mHeigth/2, radius - strokeWidth, mPaint);
        }
    }

EmbossMaskFilterView

EmbossMaskFilter 用来设置浮雕效果,其原理是模拟光照效果,靠近光的一面显得亮一点,远离光的一面显得暗一点,这样就通过颜色的亮暗营造出浮雕的3D立体效果。
构造函数:

public EmbossMaskFilter(float[] direction, float ambient, float specular, float blurRadius)

direction 是float数组,定义长度为3的数组[x,y,z],来指定光源的方向
ambient 取值在0到1之间,定义背景光 或者说是周围光
specular 定义镜面反射系数
blurRadius 模糊半径

direction 代表光源的坐标系,可以这样想想,如果所绘制的物体在原点,direction代表光源的左标,根据光源的位置不同,可以显示不同的效果。如果Z轴为负,就是在物体的后边,显示要暗一些,如果在原点,就和物体重叠,显示为黑色。显示的效果还要和环境光ambient和镜面反射specular有关系。环境光的强弱同样会影响效果。镜面反射specular的含义是根据我们学习的光的反射定律,理性情况下所有的光先都被反射回去,实际情况下光的反射要有一定的损失,镜子算是镜面反射比较强的例子。

这个API同样不支持硬件加速,需要设置:

setLayerType(LAYER_TYPE_SOFTWARE, null);

paint_EmbossMaskFilter.png
    static public class EmbossMaskFilterView extends PaintCanvasView{

        @Override
        protected void onChildDraw(Canvas canvas) {

            int strokeWidth = 20;
            int radius = mWidth/8;
            mPaint.setStrokeWidth(strokeWidth);
            mPaint.setColor(Color.RED);

            mPaint.setMaskFilter(new EmbossMaskFilter(new float[] { 1, 1, 1F }, 0.1F, 8, 3));
            canvas.drawCircle(mWidth/3/2,   mHeigth/2, radius - strokeWidth, mPaint);

            mPaint.setMaskFilter(new EmbossMaskFilter(new float[] { 1, 1, -1F }, 0.1F, 8, 3));
            canvas.drawCircle(mWidth*3/3/2, mHeigth/2, radius - strokeWidth, mPaint);

            mPaint.setMaskFilter(new EmbossMaskFilter(new float[] { 0, 0, 1F }, 0.1F, 8, 3));
            canvas.drawCircle(mWidth*5/3/2, mHeigth/2, radius - strokeWidth, mPaint);
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,295评论 6 512
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,928评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,682评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,209评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,237评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,965评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,586评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,487评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,016评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,136评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,271评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,948评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,619评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,139评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,252评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,598评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,267评论 2 358

推荐阅读更多精彩内容