1.Android canvas基本API:
矩形的点: drawPoint()
线: drawLine()
矩形:drawRect()
多边形:drawVertices()
弧:drawArc
oval :指定圆弧的外轮廓矩形区域。
startAngle: 圆弧起始角度,单位为度。
sweepAngle: 圆弧扫过的角度,顺时针方向,单位为度,从右中间开始为零度。
useCenter: 如果为True时,在绘制圆弧时将圆心包括在内,通常用来绘制扇形
椭圆:drawOval
绘制文本:drawText
指定位置绘制文本: drawPosText
绘制路径:drawPath() //其实位置默认是控件左上角(0,0) ,如果想让起始位置改变只需要调用mPath.moveTo(x,y);
圆形:drawCircle()//也能绘制圆角矩形
设置抗锯齿:setAntiAlias()
设置颜色:setColor();
设置ARGB:setARGB()
设置字体大小:setTextSize()
设置画笔风格:setStyle()//空心:STROKE 实心:FILL
设置空心边框的宽度: setStrokeWidth();
Canvas.save() 保存画布,后续操作可以理解为在一个新的图层上操作一样
Canvas.restore() 将save()后绘制的图像与save()之前的图像进行合并
Canvas.translate(x, y);移动至(x,y)坐标点
Canvas.rotate(X);画布旋转X度
canvas.scale(scale, scale,Width/2,Height/2);//以中心点缩放
canvas.scale(scale, scale);//以(0,0)位中心进行缩放
public class ScaleView extends View {
private Paint paintBot = null;
private Bitmap mRobotBitmap = null;
private float dx = 0;
private float dy = 0;
private float scale = 1f;
private PointF pointF = new PointF();
private final int ACTION_DOWN = 1;
private final int ACTION_POINTER_DOWN = 2;
private final int ACTION_POINTER_UP = 0;
private int mode = ACTION_POINTER_UP;
private float old_x_down = 0;
private float old_y_down = 0;
private float old_translate_x = 0;
private float old_translate_y = 0;
private float oldScale = 1;
private float oldDist = 1f;
private int Height = 0;
private int Width = 0;
public ScaleView(Context context) {
super(context);
init();
}
public ScaleView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ScaleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void init() {
mRobotBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Matrix matrix = new Matrix();
matrix.setScale(0.7f, 0.7f);
mRobotBitmap = Bitmap.createBitmap(mRobotBitmap, 0, 0, mRobotBitmap.getWidth(), mRobotBitmap.getHeight(), matrix, true);
//图标
paintBot = new Paint();
paintBot.setAntiAlias(true);
paintBot.setDither(true);
paintBot.setFilterBitmap(true);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
Width = w; // 获取宽度
Height = h; // 获取高度
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.scale(scale, scale, Width / 2, Height / 2);
canvas.translate(dx, dy);
canvas.drawBitmap(mRobotBitmap, Width / 2, Height / 2, paintBot);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mode = ACTION_DOWN;
old_x_down = event.getX();
old_y_down = event.getY();
break;
case MotionEvent.ACTION_POINTER_DOWN:
mode = ACTION_POINTER_DOWN;
oldDist = spacing(event);
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
pointF.set(x / 2, y / 2);
break;
case MotionEvent.ACTION_MOVE:
if (mode == ACTION_POINTER_DOWN) {
float newDist = spacing(event);
float newScale = (newDist) / oldDist * oldScale;
if (newScale > 2) {
newScale = 2;
}
if (newScale < 1) {
newScale = 1;
}
scale = newScale;
oldDist = newDist;
oldScale = newScale;
} else if (mode == ACTION_DOWN) {
float new_d_x = event.getX() - old_x_down + old_translate_x;
float new_d_y = event.getY() - old_y_down + old_translate_y;
dx = new_d_x;
dy = new_d_y;
old_x_down = event.getX();
old_y_down = event.getY();
old_translate_x = dx;
old_translate_y = dy;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode = ACTION_POINTER_UP;
break;
}
invalidate();
return true;
}
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return (float) Math.sqrt(x * x + y * y);
}
public void release() {
if (mRobotBitmap != null && !mRobotBitmap.isRecycled()) {
mRobotBitmap.recycle();
mRobotBitmap = null;
}
}
}
2.SurfaceView和View的区别:
- View主动使用于主动更新的情况,SurfaceView主动使用于被动更新(频繁刷新);
- 一般情况下,SurfaceView需要在子线程中进行页面刷新;
- View在绘图时没有使用双缓存机制,而SurfaceView在底层使用机制中就已经实现了双缓存机制;
总结一句话就是:
如果你自定义View需要频繁刷新,或者刷新时数据处理量比较大,那么你可以考虑使用SurfaceView来代替View;
public class SurfaceViewTemplate extends SurfaceView implements SurfaceHolder.Callback, Runnable {
private SurfaceHolder mHolder;
private Canvas mCanvas;
private boolean mIsDrawing;
private Path mPath;
private Paint mPaint;
public SurfaceViewTemplate(Context context) {
super(context);
initView();
}
public SurfaceViewTemplate(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public SurfaceViewTemplate(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
private void initView() {
mHolder = getHolder();
mHolder.addCallback(this);
setFocusable(true);
setFocusableInTouchMode(true);
this.setKeepScreenOn(true);
mPaint= new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG);
mPaint.setStrokeWidth(10f);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setAntiAlias(true);
mPaint.setColor(Color.RED);
mPath = new Path();
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
mIsDrawing = true;
new Thread(this).start();
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mIsDrawing = false;
}
@Override
public void run() {
while (mIsDrawing) {
draw();
}
}
private void draw() {
try {
mCanvas = mHolder.lockCanvas();
mCanvas.drawColor(Color.WHITE);
mCanvas.drawPath(mPath, mPaint);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (mCanvas != null) {
mHolder.unlockCanvasAndPost(mCanvas);
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mPath.moveTo(x,y);
break;
case MotionEvent.ACTION_MOVE:
mPath.lineTo(x,y);
break;
}
return true;
}
}
3.Later图层:
saveLater()和saveLayerAlpha()将一个图层入栈,使用restore()、restoreToCount()将图层出栈;
入栈时候,后面所有操作都会发生在这个图层上,出栈的时候.则会将图层绘制到上层Canvas上;
4.颜色矩阵(ColorMatrix):
设置色调:
setRotate(int axis,float degree);第一个参数分别用:0,1,2代表Red,Green,Blue;
ColorMatrix matrix = new ColorMatrix();
matrix.setRotate(0,mHueValue);
matrix.setRotate(1,mHueValue);
matrix.setRotate(2,mHueValue);
设置饱和度:
setSaturation():饱和度为0时,图像会变成灰度图像;
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(saturation);
设置亮度:
setScale():亮度为0时,图像会变全黑;
ColorMatrix lumMatrix = new ColorMatrix();
lumMatrix.setScale(lum,lum,lum,1);
叠加效果:
postConcat():将矩阵的作用效果混合,生成叠加处理后的效果
ColorMatrix matrix = new ColorMatrix();
matrix.postConcat(hueMatrix);
matrix.postConcat(saturationMatrix);
matrix.postConcat(lumMatrix);
注意事项:Paint类需要通过setColorFilter()来将colorMatrix构造的colorMatrixColorFilter对象传进来,并
使用这个paint来绘制原来的图像,从而将颜色阵列作用到原图上;
paint.setColorFilter(new ColorMatrixColorFilter(matrix));
像素点分析:
Bitmap.getPixels(pixels,offset,stride,x,y,width,height);
1.pixels:接收位图颜色值的数组
2.offset:写入pixels[]中的第一个像素索引值
3.stride:pixels[]中的行间距
4.x:第一像素的x坐标值
5.y:第一像素点的y坐标值
6.width:从每一行中读取的像素宽度
7.height:读取的行数
一般用法:
int oldPx[] =new int[Width*Height];
int newPx[] =new int[Width*Height];
int color;
int r,g,b,a;
for (int i=0;i<Width;i++){
color = oldPx[i];
r =Color.red(color);
g =Color.green(color);
b =Color.blue(color);
a =Color.alpha(color);
r = 255 - r;
g = 255 - g;
b = 255 - b;
if(r>255){
r=255;
} else if(r<0){
r=0;
}
if(g>255){
g=255;
} else if(g<0){
g=0;
}
if(b>255){
b=255;
} else if(b<0){
b=0;
}
newPx[i] = Color.argb(a,r,g,b);
}
bitmap.getPixels(newPx,0,bm.getWidth(),0,0,width,height);
老照片算法:
rl = (int)(0.393*r + 0.769*g + 0.189*b);
gl = (int)(0.349*r + 0.686*g + 0.168*b);
bl = (int)(0.272*r + 0.534*g + 0.131*b);
浮雕效果:
若存在ABC三个像素点,要求对B点对应的浮雕效果算法:
B.r = C.R - B.r + 127;
B.g = C.g - B.g + 127;
B.b = C.b - B.b + 127;
底片效果:
B.r = 255 - B.r;
B.g = 255 - B.g;
B.b = 255 - B.b;
矩阵变化:
初始化的矩阵为:
⎡ 1 0 0 0 0 ⎤ 0
⎢ 0 1 0 0 0 ⎥ 6
⎢ 0 0 1 0 0 ⎥ 12
⎣ 0 0 0 1 0 ⎦ 18
规则是: 横*竖
图片中的符号含义:
a, b, c, d, e 表示三原色中的红色
f, g, h, i, j 表示三原色中的绿色
k, l, m, n, o 表示三原色中的蓝色
p, q, r, s, t 表示颜色的透明度
PorterDuff.Mode: 原始图片 dst 后绘制 src
5.XML绘图:
1.Shape属性:
1)..Corners:定义圆角;
<corners //定义圆角
android:radius="dimension" //全部的圆角半径
android:topLeftRadius="dimension" //左上角的圆角半径
android:topRightRadius="dimension" //右上角的圆角半径
android:bottomLeftRadius="dimension" //左下角的圆角半径
android:bottomRightRadius="dimension" /> //右下角的圆角半径
2).solid:填充内部颜色
<solid android:color="@color/colorAccent"/>
3).gradient:定义渐变色:
<gradient
android:angle="integer"
android:centerX="integer"
android:centerY="integer"
android:centerColor="integer"
android:endColor="color"
android:gradientRadius="integer"
android:startColor="color"
android:type=["linear" | "radial" | "sweep"]
android:useLevel=["true" | "false"] />
4).stoke:指定边框:
<stroke
android:width="5dp"
android:color="@android:color/holo_green_dark"
android:dashWidth="10dp"
android:dashGap="10dp"/>
shape示例代码:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="5dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp"
android:bottomLeftRadius="5dp"
android:bottomRightRadius="5dp"/>
<!--angle:渐变角度-->
<gradient
android:angle="45"
android:centerX="0.5"
android:centerY="0.5"
android:centerColor="@android:color/black"
android:endColor="@color/colorAccent"
android:gradientRadius="5dp"
android:startColor="@color/colorPrimaryDark"
android:type="linear"
android:useLevel="false"/>
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
<!--填充颜色-->
<!--<solid android:color="@android:color/holo_blue_bright"/>-->
<!--dashGap:虚线间距宽度-->
<!--dashWidth:虚线宽度-->
<stroke
android:width="5dp"
android:color="@android:color/holo_green_dark"
android:dashWidth="10dp"
android:dashGap="10dp"/>
2..selector:可以根据事件设置不同图像;
1).shape的形状,默认为矩形,可以设置为矩形(rectangle)、椭圆形(oval)、线性形状(line)、环形(ring)
2).下面的属性只有在android:shape="ring时可用:
a).android:innerRadius 尺寸,内环的半径。
b).android:innerRadiusRatio 浮点型,以环的宽度比率来表示内环的半径,
c).android:thickness 尺寸,环的厚度
d).android:thicknessRatio 浮点型,以环的宽度比率来表示环的厚度,例如,如果android:thicknessRatio="2",
e).android:useLevel boolean值,如果当做是LevelListDrawable使用时值为true,否则为false.
selector示例代码:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!--是否按下-->
<item android:state_pressed="true">
<!--设置为矩形-->
<shape android:shape="rectangle">
<!--填充颜色-->
<solid android:color="@color/colorAccent" />
<!--圆形角-->
<corners android:radius="5dp" />
<padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle">
<solid android:color="@color/colorPrimaryDark" />
<corners android:radius="5dp" />
<padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp" />
</shape>
</item>
</selector>
6.自定义绘制步骤:
1.方法: 重写绘制方法(最常用:onDraw());
2.绘制的关键:Canvas
a).Canvas的绘制类方法:drawXXX() (关键参数:Paint);
b).Canvas的辅助类方法:范围裁切(clipxxx())和几何变形(Matrix)
3.使用不同的绘制方法来控制遮盖关系;
4.在View中比较重要的回调方法:
a).onFinishInflate();//在XML加载组件后回调;
b).onSizeChanged();//组件大小改变时回调;
c).onMeasure();//回调方法来进行测量;
b).onLayout();//回调该方法来确定显示的位置;
d).onTouchEvent();//监听到触摸事件时回调.
7.Canvas 对绘制的辅助:
1.范围裁切:
a).clipRect()和cliPath();
2.几何变形:
a).Canvas.translate/rotate/scale/skew();
b).Matrix.pre/postTranslate/Rotate/Scate/Skew() 及自定义转化;
c).Camera.rotate()Camera.setLocation:三维变换
8.属性动画
1.ViewPropertyAnimator
a).View,animate();
b).配合translationX() translationY() alpha() rotation() scaleX() 等方法
2.ObjectAnimator
a).ObjectAnimator.ofXXX() 创建Animator对象
b).start()执行动画;
3.功能:
a).setDuration;设置时长;
b).setInterpolator():设置速度模型;
c).设置监听器;
9.View提供获取坐标的方法:
1.getTop(): 获取到的是View自身的顶边到其父布局顶边的距离;
2.getLeft(): 获取到的是View自身的左边到其父布局的左边的距离;
3.getRight(): 获取到的是View自身的右边到其父布局的左边的距离;
4.getBottom(): 获取到的是View自身的底边到其父布局顶边的距离;
10.MotionEvent提供的方法:
1.getX():获取点击事件距离控件左边的距离,即视图坐标;
2.getY():获取点击事件距离控件顶边的距离,即视图坐标;
3.getRawX(): 获取点击事件距离整个屏幕左边的距离,即绝对坐标;
4.getRawY(): 获取点击事件距离整个屏幕顶边的距离,即绝对坐标;
关于ColorMatrix: https://www.jianshu.com/p/ebda27f061e3
参考:
https://www.cnblogs.com/MianActivity/p/5867776.html
https://juejin.im/post/5962a3746fb9a06ba2687226
《Android群英传》
网友评论