Android Canvas实现自定义形状的image

2019-11-17  本文已影响0人  平凡小天地

灵活自定义imageview的形状

//设置背景色

canvas.drawARGB(255, 139, 197, 186);

int canvasWidth = canvas.getWidth();

int canvasHeight = canvas.getHeight();

int layerId = canvas.saveLayer(0, 0, canvasWidth, canvasHeight, null, Canvas.ALL_SAVE_FLAG);

int r = canvasWidth / 2;

//根据图片生成bitmapshader

paint.setColor(0xFFFFCC44);

Bitmap bitmap = Bitmap.createBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.xihu));

bitmap = scaleBitmap(bitmap,2*r,2*r);

BitmapShader bitmapShader = new BitmapShader(bitmap,Shader.TileMode.CLAMP,Shader.TileMode.CLAMP);

paint.setShader(bitmapShader);

canvas.drawCircle(r, r, r, paint);

//使用CLEAR作为PorterDuffXfermode绘制蓝色的矩形

paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));// clear 到背景颜色那一层

canvas.drawCircle(r*3f-50, r, r , paint);

//最后将画笔去除Xfermode

paint.setXfermode(null);

canvas.restoreToCount(layerId);
/**

 * 根据给定的宽和高进行拉伸

* @param origin    原图

* @param newWidth  新图的宽

* @param newHeight 新图的高

* @return new Bitmap

 */

private Bitmap scaleBitmap(Bitmap origin, int newWidth, int newHeight) {

    if (origin == null) {

        return null;

    }

    int height = origin.getHeight();

    int width = origin.getWidth();

    float scaleWidth = ((float) newWidth) / width;

    float scaleHeight = ((float) newHeight) / height;

    Matrix matrix = new Matrix();

    matrix.postScale(scaleWidth, scaleHeight);// 使用后乘

    Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);

    if (!origin.isRecycled()) {

        origin.recycle();

    }

    return newBM;

}
r1McLAqQYLVfWL6Ducp97ZuhdH1OWBRhZiWv2OEBSZYGCWP7ps.png

Android graphics使用

(1)绘制形状Canvas

[图片上传失败...(image-3c6580-1573961626362)]

Path可自由实现各种自定义形状:直线,圆弧,贝塞尔曲线等等

Path path = new Path();

RectF rect = new RectF(300,300,1000,800);

mPaint.setColor(Color.GRAY);

mPaint.setStyle(Style.FILL);

canvas.drawRect(rect, mPaint);

mPaint.setColor(Color.BLACK);

mPaint.setStyle(Style.STROKE);

path.lineTo(100, 100); //用path画一条从(0,0)到(100,100)的直线

path.arcTo(rect, 90, 180); //用arcTo方法画一段圆弧

canvas.drawPath(path, mPaint); //直线终点(100,100)与圆弧起点会连成一条直线

(2)绘制效果Paint

[图片上传失败...(image-f699f4-1573961626362)]

(3)绘制位置坐标

[图片上传失败...(image-f432a2-1573961626362)]

(4)变换处理Matrix

例:将bitmap放大2倍

Matrix matrix = new Matrix();

matrix.postScale(2, 2);// 使用后乘

Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);

(5)自定义动画效果

[图片上传失败...(image-47702a-1573961626362)]

[图片上传失败...(image-b5fd46-1573961626362)]

参考文档

graphic基本操作例子

上一篇下一篇

猜你喜欢

热点阅读