先來看一下Canvas
Canvas 用來提供draw方法的調用。繪制東西需要4個基本的組建:一個bitmap用來存放像素,一個canvas用來提供draw方法的調用(往bitmap里寫入),原始繪制元素(e.g.Rect, Path, text,Bitmap), 一個paint。
看一下canvas的主要方法:
public class HappinessView extends View {private static final float CIRCLE_RADIUS =
100f;
private static final float faceRadiusToEyeRadiusRadio =
10f;
private static final float faceRadiusToEyeOffsetRadio =
3f;
private static final float faceRadiusToEyeSeparationRadio =
1.5f;
private static final float faceRadiusToMouthWidthRadio =
1;
private static final float faceRadiusToMouthHeightRadio =
3;
private static final float faceRadiusToMouthOffsetRatio =
3;
private enum Eye{ Left, Right}
public HappinessView(Context context) {
super(context);}
@Overrideprotected void onDraw(Canvas canvas) {
super.onDraw(canvas);Paint paint =
new Paint();paint.setStyle(Paint.Style.STROKE);paint.setAntiAlias(
true);paint.setColor(Color.BLUE);canvas.drawCircle(
100,
100, CIRCLE_RADIUS, paint);circlePathForEye(canvas, paint, Eye.Left);circlePathForEye(canvas, paint, Eye.Right);bezierPathForSmile(canvas, paint);}
private void bezierPathForSmile(Canvas canvas, Paint paint) {
float fractionOfMaxSmile = -
1f;
float mouthWidth = CIRCLE_RADIUS / faceRadiusToMouthWidthRadio;
float mouthHeight = CIRCLE_RADIUS / faceRadiusToMouthHeightRadio;
float mouthVerticalOffset = CIRCLE_RADIUS / faceRadiusToMouthOffsetRatio;
float smileHeight = Math.max(Math.min(fractionOfMaxSmile,
1), -
1) * mouthHeight;
float startPointX =
100 - mouthWidth /
2;
float startPointY =
100 + mouthVerticalOffset;
float endPointX = startPointX + mouthWidth;
float endPointY = startPointY;
float point1X = startPointX + mouthWidth /
3;
float point1Y = startPointY + smileHeight;
float point2X = endPointX - mouthWidth /
3;
float point2Y = point1Y;Path path =
new Path();path.moveTo(startPointX, startPointY);path.cubicTo( point1X, point1Y, point2X, point2Y, endPointX, endPointY);canvas.drawPath(path, paint);}
private void circlePathForEye(Canvas canvas, Paint paint, Eye eye){
float eyeRadius =
100 / faceRadiusToEyeRadiusRadio;
float eyeVerticalOffset =
100 / faceRadiusToEyeOffsetRadio;
float eyeHorizontalSeparation =
100 / faceRadiusToEyeSeparationRadio;
float eyeY =
100 - eyeVerticalOffset;
float eyeX =
100;
switch (eye) {
case Left:eyeX = eyeX - eyeHorizontalSeparation /
2;
break;
case Right:eyeX = eyeX + eyeHorizontalSeparation /
2;
break;}canvas.drawCircle(eyeX, eyeY, eyeRadius, paint);}
}
一個簡單的笑臉圖形。
總結
以上是生活随笔為你收集整理的绘制基础知识-canvas paint的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。