导读:// 覆盖drawRect方法,你可以在此自定义绘画和动画 - (void)drawRect:(CGRect)rect { //An opaque type that represents a Quartz 2D drawin
// 覆盖drawRect方法,你可以在此自定义绘画和动画
- (void)drawRect:(CGRect)rect
{
//An opaque type that represents a Quartz 2D drawing environment
//一个不透明类型的Quartz 2D绘画环境,相当于一个画布,你可以在上面任意绘画
CGContextRef context = UIGraphicsGetCurrentContext();
/写文字/
CGContextSetRGBFillColor (context, 1, 0, 0, 10);//设置填充颜色
UIFont font = [UIFont boldSystemFontOfSize:150];//设置
[@"画圆:" drawInRect:CGRectMake(10, 20, 80, 20) withFont:font];
[@"画线及孤线:" drawInRect:CGRectMake(10, 80, 100, 20) withFont:font];
[@"画矩形:" drawInRect:CGRectMake(10, 120, 80, 20) withFont:font];
[@"画扇形和椭圆:" drawInRect:CGRectMake(10, 160, 110, 20) withFont:font];
[@"画三角形:" drawInRect:CGRectMake(10, 220, 80, 20) withFont:font];
[@"画圆角矩形:" drawInRect:CGRectMake(10, 260, 100, 20) withFont:font];
[@"画贝塞尔曲线:" drawInRect:CGRectMake(10, 300, 100, 20) withFont:font];
[@":" drawInRect:CGRectMake(10, 340, 80, 20) withFont:font];
/画圆/
//边框圆
CGContextSetRGBStrokeColor(context,1,1,1,10);//画笔线的颜色
CGContextSetLineWidth(context, 10);//线的宽度
//void CGContextAddArc(CGContextRef c,CGFloat x, CGFloat y,CGFloat radius,CGFloat startAngle,CGFloat endAngle, int clockwise)1弧度=180°/π (≈573°) 度=弧度×180°/π 360°=360×π/180 =2π 弧度
// x,y为圆点坐标,radius半径,startAngle为开始的弧度,endAngle为 结束的弧度,clockwise 0为顺时针,1为逆时针。
CGContextAddArc(context, 100, 20, 15, 0, 2PI, 0); //添加一个圆
CGContextDrawPath(context, kCGPathStroke); //绘制路径
//填充圆,无边框
CGContextAddArc(context, 150, 30, 30, 0, 2PI, 0); //添加一个圆
CGContextDrawPath(context, kCGPathFill);//绘制填充
//画大圆并填充颜
UIColoraColor = [UIColor colorWithRed:1 green:00 blue:0 alpha:1];
CGContextSetFillColorWithColor(context, aColorCGColor);//填充颜色
CGContextSetLineWidth(context, 30);//线的宽度
CGContextAddArc(context, 250, 40, 40, 0, 2PI, 0); //添加一个圆
//kCGPathFill填充非零绕数规则,kCGPathEOFill表示用奇偶规则,kCGPathStroke路径,kCGPathFillStroke路径填充,kCGPathEOFillStroke表示描线,不是填充
CGContextDrawPath(context, kCGPathFillStroke); //绘制路径加填充
/画线及孤线/
//画线
CGPoint aPoints[2];//坐标点
aPoints[0] =CGPointMake(100, 80);//坐标1
aPoints[1] =CGPointMake(130, 80);//坐标2
//CGContextAddLines(CGContextRef c, const CGPoint points[],size_t count)
//points[]坐标数组,和count大小
CGContextAddLines(context, aPoints, 2);//添加线
CGContextDrawPath(context, kCGPathStroke); //根据坐标绘制路径
//画笑脸弧线
//左
CGContextSetRGBStrokeColor(context, 0, 0, 1, 1);//改变画笔颜色
CGContextMoveToPoint(context, 140, 80);//开始坐标p1
//CGContextAddArcToPoint(CGContextRef c, CGFloat x1, CGFloat y1,CGFloat x2, CGFloat y2, CGFloat radius)
//x1,y1跟p1形成一条线的坐标p2,x2,y2结束坐标跟p3形成一条线的p3,radius半径,注意, 需要算好半径的长度,
CGContextAddArcToPoint(context, 148, 68, 156, 80, 10);
CGContextStrokePath(context);//绘画路径
//右
CGContextMoveToPoint(context, 160, 80);//开始坐标p1
//CGContextAddArcToPoint(CGContextRef c, CGFloat x1, CGFloat y1,CGFloat x2, CGFloat y2, CGFloat radius)
//x1,y1跟p1形成一条线的坐标p2,x2,y2结束坐标跟p3形成一条线的p3,radius半径,注意, 需要算好半径的长度,
CGContextAddArcToPoint(context, 168, 68, 176, 80, 10);
CGContextStrokePath(context);//绘画路径
//右
CGContextMoveToPoint(context, 150, 90);//开始坐标p1
//CGContextAddArcToPoint(CGContextRef c, CGFloat x1, CGFloat y1,CGFloat x2, CGFloat y2, CGFloat radius)
//x1,y1跟p1形成一条线的坐标p2,x2,y2结束坐标跟p3形成一条线的p3,radius半径,注意, 需要算好半径的长度,
CGContextAddArcToPoint(context, 158, 102, 166, 90, 10);
CGContextStrokePath(context);//绘画路径
//注,如果还是没弄明白怎么回事,请参考:http://donbeblog163com/blog/static/138048021201052093633776/
/画矩形/
CGContextStrokeRect(context,CGRectMake(100, 120, 10, 10));//画方框
CGContextFillRect(context,CGRectMake(120, 120, 10, 10));//填充框
//矩形,并填弃颜色
CGContextSetLineWidth(context, 20);//线的宽度
aColor = [UIColor blueColor];//blue蓝色
CGContextSetFillColorWithColor(context, aColorCGColor);//填充颜色
aColor = [UIColor yellowColor];
CGContextSetStrokeColorWithColor(context, aColorCGColor);//线框颜色
CGContextAddRect(context,CGRectMake(140, 120, 60, 30));//画方框
CGContextDrawPath(context, kCGPathFillStroke);//绘画路径
//矩形,并填弃渐变颜色
//关于颜色参考http://blogsinacomcn/s/blog_6ec3c9ce01015v3chtml
//http://blogcsdnnet/reylen/article/details/8622932
//第一种填充方式,第一种方式必须导入类库quartcore并#import <QuartzCore/QuartzCoreh>,这个就不属于在context上画,而是将层插入到view层上面。那么这里就设计到Quartz Core 图层编程了。
CAGradientLayer gradient1 = [CAGradientLayer layer];
gradient1frame = CGRectMake(240, 120, 60, 30);
gradient1colors = [NSArray arrayWithObjects:(id)[UIColor whiteColor]CGColor,
(id)[UIColor grayColor]CGColor,
(id)[UIColor blackColor]CGColor,
(id)[UIColor yellowColor]CGColor,
(id)[UIColor blueColor]CGColor,
(id)[UIColor redColor]CGColor,
(id)[UIColor greenColor]CGColor,
(id)[UIColor orangeColor]CGColor,
(id)[UIColor brownColor]CGColor,nil];
[selflayer insertSublayer:gradient1 atIndex:0];
//第二种填充方式
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
CGFloat colors[] =
{
1,1,1, 100,
1,1,0, 100,
1,0,0, 100,
1,0,1, 100,
0,1,1, 100,
0,1,0, 100,
0,0,1, 100,
0,0,0, 100,
};
CGGradientRef gradient = CGGradientCreateWithColorComponents
(rgb, colors, NULL, sizeof(colors)/(sizeof(colors[0])4));//形成梯形,渐变的效果
CGColorSpaceRelease(rgb);
//画线形成一个矩形
//CGContextSaveGState与CGContextRestoreGState的作用
/
CGContextSaveGState函数的作用是将当前图形状态推入堆栈。之后,您对图形状态所做的修改会影响随后的描画操作,但不影响存储在堆栈中的拷贝。在修改完成后,您可以通过CGContextRestoreGState函数把堆栈顶部的状态弹出,返回到之前的图形状态。这种推入和弹出的方式是回到之前图形状态的快速方法,避免逐个撤消所有的状态修改;这也是将某些状态(比如裁剪路径)恢复到原有设置的唯一方式。
/
CGContextSaveGState(context);
CGContextMoveToPoint(context, 220, 90);
CGContextAddLineToPoint(context, 240, 90);
CGContextAddLineToPoint(context, 240, 110);
CGContextAddLineToPoint(context, 220, 110);
CGContextClip(context);//context裁剪路径,后续操作的路径
//CGContextDrawLinearGradient(CGContextRef context,CGGradientRef gradient, CGPoint startPoint, CGPoint endPoint,CGGradientDrawingOptions options)
//gradient渐变颜色,startPoint开始渐变的起始位置,endPoint结束坐标,options开始坐标之前or开始之后开始渐变
CGContextDrawLinearGradient(context, gradient,CGPointMake
(220,90) ,CGPointMake(240,110),
kCGGradientDrawsAfterEndLocation);
CGContextRestoreGState(context);// 恢复到之前的context
//再写一个看看效果
CGContextSaveGState(context);
CGContextMoveToPoint(context, 260, 90);
CGContextAddLineToPoint(context, 280, 90);
CGContextAddLineToPoint(context, 280, 100);
CGContextAddLineToPoint(context, 260, 100);
CGContextClip(context);//裁剪路径
//说白了,开始坐标和结束坐标是控制渐变的方向和形状
CGContextDrawLinearGradient(context, gradient,CGPointMake
(260, 90) ,CGPointMake(260, 100),
kCGGradientDrawsAfterEndLocation);
CGContextRestoreGState(context);// 恢复到之前的context
//下面再看一个颜色渐变的圆
CGContextDrawRadialGradient(context, gradient, CGPointMake(300, 100), 00, CGPointMake(300, 100), 10, kCGGradientDrawsBeforeStartLocation);
/画扇形和椭圆/
//画扇形,也就画圆,只不过是设置角度的大小,形成一个扇形
aColor = [UIColor colorWithRed:0 green:1 blue:1 alpha:1];
CGContextSetFillColorWithColor(context, aColorCGColor);//填充颜色
//以10为半径围绕圆心画指定角度扇形
CGContextMoveToPoint(context, 160, 180);
CGContextAddArc(context, 160, 180, 30, -60 PI / 180, -120 PI / 180, 1);
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFillStroke); //绘制路径
//画椭圆
CGContextAddEllipseInRect(context, CGRectMake(160, 180, 20, 8)); //椭圆
CGContextDrawPath(context, kCGPathFillStroke);
/画三角形/
//只要三个点就行跟画一条线方式一样,把三点连接起来
CGPoint sPoints[3];//坐标点
sPoints[0] =CGPointMake(100, 220);//坐标1
sPoints[1] =CGPointMake(130, 220);//坐标2
sPoints[2] =CGPointMake(130, 160);//坐标3
CGContextAddLines(context, sPoints, 3);//添加线
CGContextClosePath(context);//封起来
CGContextDrawPath(context, kCGPathFillStroke); //根据坐标绘制路径
/画圆角矩形/
float fw = 180;
float fh = 280;
CGContextMoveToPoint(context, fw, fh-20); // 开始坐标右边开始
CGContextAddArcToPoint(context, fw, fh, fw-20, fh, 10); // 右下角角度
CGContextAddArcToPoint(context, 120, fh, 120, fh-20, 10); // 左下角角度
CGContextAddArcToPoint(context, 120, 250, fw-20, 250, 10); // 左上角
CGContextAddArcToPoint(context, fw, 250, fw, fh-20, 10); // 右上角
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFillStroke); //根据坐标绘制路径
/画贝塞尔曲线/
//二次曲线
CGContextMoveToPoint(context, 120, 300);//设置Path的起点
CGContextAddQuadCurveToPoint(context,190, 310, 120, 390);//设置贝塞尔曲线的控制点坐标和终点坐标
CGContextStrokePath(context);
//三次曲线函数
CGContextMoveToPoint(context, 200, 300);//设置Path的起点
CGContextAddCurveToPoint(context,250, 280, 250, 400, 280, 300);//设置贝塞尔曲线的控制点坐标和控制点坐标终点坐标
CGContextStrokePath(context);
//
UIImage image = [UIImage imageNamed:@"applejpg"];
[image drawInRect:CGRectMake(60, 340, 20, 20)];//在坐标中画出
// [image drawAtPoint:CGPointMake(100, 340)];//保持大小在point点开始画,可以把注释去掉看看
CGContextDrawImage(context, CGRectMake(100, 340, 20, 20), imageCGImage);//使用这个使上下颠倒了,参考http://blogcsdnnet/koupoo/article/details/8670024
// CGContextDrawTiledImage(context, CGRectMake(0, 0, 20, 20), imageCGImage);//平铺图
}
@end
android 使用百度地图画轨迹
import androidcontentContext;import androidgraphicsCanvas;
import androidgraphicsColor;
import androidgraphicsPaint;
import androidgraphicsPaintStyle;
import androidgraphicsPath;
import androidgraphicsPoint;
import androidosBundle;
import combaidumapapiBMapManager;
import combaidumapapiGeoPoint;
import combaidumapapiMapActivity;
import combaidumapapiMapController;
import combaidumapapiMapView;
import combaidumapapiOverlay;
import combaidumapapiProjection;
public class BaiduMapActivity extends MapActivity {
private Context mContext;
private MapView mapView;
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private GeoPoint gpoint1, gpoint2, gpoint3;// 连线的点
@Override
protected void onCreate(Bundle arg0) {
superonCreate(arg0);
setContentView(Rlayoutbaidumap_layout);
BaseApplication baseApp = (BaseApplication) thisgetApplication();
if (baseAppmBMapManage == null) {
baseAppmBMapManage = new BMapManager(mContext);
baseAppmBMapManageinit(baseAppmStrKey,
new BaseApplicationMyGeneralListener());
}
baseAppmBMapManagestart();
superinitMapActivity(baseAppmBMapManage);// 初始化map sdk
mapView = (MapView) findViewById(RidbmapView);
mapViewsetBuiltInZoomControls(true);
// 设置在缩放动画过程中也显示overlay,默认为不绘制
mapViewsetDrawOverlayWhenZooming(true);
// RouteLine routeLine =
// (RouteLine)getIntent()getSerializableExtra("routeLine");
//这里画点和连接线
MyOverlay myOverlay = new MyOverlay();
mapViewgetOverlays()add(myOverlay);
MapController mapController = mapViewgetController();
mapControllerzoomIn();
gpoint1 = new GeoPoint((int) (2259316 10),
(int) (11396279 10));
gpoint2 = new GeoPoint((int) (2259245 10),
(int) (11396226 10));
gpoint3 = new GeoPoint((int) (2259121 10),
(int) (11396066 10));
mapControlleranimateTo(gpoint1);//设置一个起点
}
class MyOverlay extends Overlay {
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
superdraw(canvas, mapView, shadow);
Projection projection = mapViewgetProjection();
Point p1 = new Point();
Point p2 = new Point();
Point p3 = new Point();
// 经度转像素
projectiontoPixels(gpoint1, p1);
projectiontoPixels(gpoint2, p2);
projectiontoPixels(gpoint3, p3);
//第一个画笔 画圆
Paint fillPaint = new Paint();
fillPaintsetColor(ColorBLUE);
fillPaintsetAntiAlias(true);
fillPaintsetStyle(StyleFILL);
// 将图画到上层
canvasdrawCircle(p1x, p1y, 50f, fillPaint);
canvasdrawCircle(p2x, p2y, 50f, fillPaint);
canvasdrawCircle(p3x, p3y, 50f, fillPaint);
//第二个画笔 画线
Paint paint = new Paint();
paintsetColor(ColorBLUE);
paintsetDither(true);
paintsetStyle(PaintStyleSTROKE);
paintsetStrokeJoin(PaintJoinROUND);
paintsetStrokeCap(PaintCapROUND);
paintsetStrokeWidth(4);
//连接
Path path = new Path();
pathmoveTo(p1x, p1y);
pathlineTo(p2x, p2y);
pathlineTo(p3x, p3y);
//画出路径
canvasdrawPath(path, paint);
}
}
}
你好,Paint mField = new Paint();
mFieldsetAntiAlias(true);
Path mFieldPath = new Path();
mFieldPathmoveTo(X1,Y1);
mFieldPathlineTo(X2,Y2);
mFieldPathlineTo(X3,Y3);
mFieldPathlineTo(X4,Y4);
mFieldPathclose();
mFieldsetARGB(200, 255, 215, 0);//设置封闭路径的填充色为金
canvasdrawPath(mFieldPath, mField);
这样绘制出来的图形为一个金矩形,不够美观,因此想到使用来填充
直接加上如下代码:
Shader mShader = new BitmapShader(fieldBitmap,ShaderTileModeREPEAT,ShaderTileModeMIRROR);
mFieldsetShader(mShader);
其中,filedBitmap为指定的,可以通过mFieldBitmap = BitmapFactorydecodeResource(thisgetResources(), Rdrawablefeild);方式获得
1、设置View,重写protectedvoidonDraw(Canvascanvas)方法2、使用onDraw中的canvas,通过Path设置三角形的三个顶点,通过drawPath方式绘制三角形示例:@OverrideprotectedvoidonDraw(Canvascanvas){superonDraw(canvas);canvasdrawText("画三角形:",10,200,p);//绘制这个三角形,你可以绘制任意多边形Pathpath=newPath();pathmoveTo(80,200);//此点为多边形的起点pathlineTo(120,250);pathlineTo(80,250);pathclose();//使这些点构成封闭的多边形canvasdrawPath(path,p);}
就
是
这
个
了
!
Hand类的代码:
Public MustInherit Class Hand
Protected gp As GraphicsPath = New GraphicsPath()
Protected gpBase As GraphicsPath = Nothing
Protected midX As Integer = 150 ‘默认的窗体
Protected midY As Integer = 150 ‘中心位置
‘构造器,得到窗体中心位置
Public Sub New(ByVal theForm As Form1)
midX = (theFormClientRectangleLeft + theFormClientRectangleRight) / 2
midY = (theFormClientRectangleTop + theFormClientRectangleBottom) / 2
End Sub
MustOverride Sub Transform(ByVal d As DateTime)
‘绘制指针路径
Overridable Sub Draw(ByVal g As Graphics)
Dim aPen As Pen = New Pen(BrushesBlack, 4F)
gDrawPath(aPen, gp)
gFillPath(BrushesBlack, gp)
aPenDispose()
End Sub
‘使用矩阵实现路径(gp)的旋转
Public Sub Rotate(ByVal angle As Double)
gp = CType(gpBaseClone(), GraphicsPath)
Dim mTransform As Matrix = New Matrix()
mTransformRotateAt(CType(angle,Single),NewPointF(midX,midY))
gpTransform(mTransform)
End Sub
End Class
为了节省篇幅,上面的代码省略了引入命名空间的语句。
下面是分针(MinuteHand)类的定义:
Public Class MinuteHand
Inherits Hand
‘构造器,生成绘制分针的路径(gp)
Public Sub New(ByVal myForm As Form1)
MyBaseNew(myForm)
gpAddLine(midX, midY, midX, 45)
gpAddLine(midX, 45, midX - 3, 50)
gpAddLine(midX - 3, 50, midX + 3, 50)
gpAddLine(midX + 3, 50, midX, 45)
gpBase = CType(gpClone(), GraphicsPath)
End Sub
‘Transform方法取得系统当前时间,并旋转时钟指针。
Public Overrides Sub Transform(ByVal d As DateTime)
Dim minuteTime As Double = (CDbl(dMinute) + CDbl(dSecond / 60))
Dim angle As Double = (CDbl(minuteTime) / 60) 360
Rotate(angle)
End Sub
End Class
对所有的指针旋转的方法都是相同的,因此在基类中实现。由于时针和秒针的实现与分针相似,所不同者,只在于构造器中绘制的指针路径不同和Transform方法中转动的角度不同,在这里就不在赘述了。
另外还需要提一下的是画时钟表面的代码,时钟表面用ClockFace类来实现。这个类首先画一个圆代表时钟,然后画上米老鼠的图案,最后在相应的位置画上数字1~12代表12个小时。
Public Sub Draw(ByVal g As Graphics)
DrawClockFace(g)
DrawImage(g)
DrawNumbers(g)
DrawPin(g)
End Sub
下面是ClockFace类的属性:
Private ClockRectangle As Rectangle
Private ClockFont As Font = New Font("Arial", 12)
Private midPoint As Point
Private ClockImage As Bitmap
Private Const IMAGEX As Integer = 50
Private Const IMAGEY As Integer = 50
DrawClockFace方法用来画时钟表面:
Private Sub DrawClockFace(ByVal g As Graphics)
gFillEllipse(BrushesWhite, ClockRectangleLeft + 10, ClockRectangleTop + 10, ClockRectangleWidth - 20, ClockRectangleHeight - 20)
gDrawEllipse(PensBlack, ClockRectangleLeft + 10, ClockRectangleTop + 10, ClockRectangleWidth - 20, ClockRectangleHeight - 20)
End Sub
然后用Graphics对象的DrawImage方法画出米老鼠的:
Private Sub DrawImage(ByVal g As Graphics)
Dim nWidth As Integer = ClockImageWidth
Dim nHeight As Integer = ClockImageHeight
Dim destRect As Rectangle = New Rectangle(midPointX - IMAGEX / 2, midPointY - IMAGEY / 2, IMAGEX, IMAGEY)
gDrawImage(ClockImage, destRect)
End Sub
数字在时钟上的位置是用sin和cos函数计算的:
Private Sub DrawNumbers(ByVal g As Graphics)
Dim count As Integer = 1
Dim a As Double
For a = 0 To 2 MathPI Step 2 MathPI / 12
Dim x As Double = (ClockRectangleWidth - 70) / 2 MathCos(a - MathPI / 3) + (ClockRectangleWidth - 70) / 2 + 25
Dim y As Double = (ClockRectangleWidth - 70) / 2 MathSin(a - MathPI / 3) + (ClockRectangleWidth - 70) / 2 + 20
gDrawString(ConvertToString(count), ClockFont, BrushesBlack, CType(x, Single), CType(y, Single), New StringFormat())
count += 1
Next
End Sub
最后是窗体文件(Form1vb):
Public Class Form1
Inherits SystemWindowsFormsForm
Private MyMinuteHand As MinuteHand
Private MyHourHand As HourHand
Private MySecondHand As SecondHand
Private TheClockFace As ClockFace
Private FirstTick As Boolean = False
‘在窗体的OnPaint事件中取得Graphics对象
Protected Overrides Sub OnPaint(ByVal e As SystemWindowsFormsPaintEventArgs)
If (FirstTick = False) Then Exit Sub
Dim g As Graphics = eGraphics
TheClockFaceDraw(g)
MyHourHandDraw(g)
MyMinuteHandDraw(g)
MySecondHandDraw(g)
TheClockFaceDrawPin(g)
End Sub
‘计时器事件
Private Sub Timer1_Tick(ByVal sender As SystemObject, ByVal e As SystemEventArgs) Handles Timer1Tick
MySecondHandTransform(DateTimeNow)
MyHourHandTransform(DateTimeNow)
MyMinuteHandTransform(DateTimeNow)
FirstTick = True
Invalidate()
1静态蛛网图
第一步就是如何将一串数据映射成下面的图表:
var data = {
"攻击力": 700,
"生命": 900,
"闪避": 500,
"暴击": 700,
"破格": 800,
"格挡": 1000,
};
复制代码
11:创建AbilityWidget组件
线新建一个StatelessWidget的组件使用AbilityPainter进行绘制
这里先定义画笔、路径等成员变量
import 'package:flutter/materialdart';
class AbilityWidget extends StatefulWidget {
@override
_AbilityWidgetState createState() => _AbilityWidgetState();
}
class _AbilityWidgetState extends State<AbilityWidget>{
@override
Widget build(BuildContext context) {
var paint = CustomPaint(
painter: AbilityPainter(),
);
return SizedBox(width: 200, height: 200, child: paint,);
}
}
class AbilityPainter extends CustomPainter {
var data = {
"攻击力": 700,
"生命": 900,
"闪避": 500,
"暴击": 700,
"破格": 800,
"格挡": 1000,
};
double mRadius = 100; //外圆半径
Paint mLinePaint; //线画笔
Paint mAbilityPaint; //区域画笔
Paint mFillPaint;//填充画笔
Path mLinePath;//短直线路径
Path mAbilityPath;//范围路径
AbilityPainter() {
mLinePath = Path();
mAbilityPath = Path();
mLinePaint = Paint()
color = Colorsblack
style = PaintingStylestroke
strokeWidth=0008 mRadius
isAntiAlias = true;
mFillPaint = Paint() //填充画笔
strokeWidth = 005 mRadius
color = Colorsblack
isAntiAlias = true;
mAbilityPaint = Paint()
color = Color(0x8897C5FE)
isAntiAlias = true;
}
@override
void paint(Canvas canvas, Size size) {
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
复制代码
12绘制外圈
为了减少变量值,让尺寸具有很好的联动性(等比扩缩),小黑条的长宽将取决于最大半径mRadius
则:小黑条长:mRadius008 小黑条宽:mRadius005 所以r2=mRadius-mRadius008
@override
void paint(Canvas canvas, Size size) {
canvastranslate(mRadius, mRadius); //移动坐标系
drawOutCircle(canvas);
}
//绘制外圈
void drawOutCircle(Canvas canvas) {
canvassave();//新建图层
canvasdrawCircle(Offset(0, 0), mRadius, mLinePaint);//圆形的绘制
double r2 = mRadius - 008 mRadius; //下圆半径
canvasdrawCircle(Offset(0, 0), r2, mLinePaint);
for (var i = 00; i < 22; i++) {//循环画出小黑条
canvassave();//新建图层
canvasrotate(360 / 22 i / 180 pi);//旋转:注意传入的是弧度(与Android不同)
canvasdrawLine(Offset(0, -mRadius), Offset(0, -r2), mFillPaint);//线的绘制
canvasrestore();//释放图层
}
canvasrestore();//释放图层
}
复制代码
13绘制内圈
同样尺寸和最外圆看齐,这里绘制有一丢丢复杂,你需要了解canvas和path的使用
看不懂的可转到canvas和path,如果看了这两篇还问绘制有什么技巧的,可转到这里
@override
void paint(Canvas canvas, Size size) {
canvastranslate(mRadius, mRadius); //移动坐标系
drawOutCircle(canvas);
drawInnerCircle(canvas);
}
//绘制内圈圆
drawInnerCircle(Canvas canvas) {
double innerRadius = 0618 mRadius;//内圆半径
canvasdrawCircle(Offset(0, 0), innerRadius, mLinePaint);
canvassave();
for (var i = 0; i < 6; i++) {//遍历6条线
canvassave();
canvasrotate(60 itoDouble() / 180 pi); //每次旋转60°
mPathmoveTo(0, -innerRadius);
mPathrelativeLineTo(0, innerRadius); //线的路径
for (int j = 1; j < 6; j++) {
mPathmoveTo(-mRadius 002, innerRadius / 6 j);
mPathrelativeLineTo(mRadius 002 2, 0);
} //加5条小线
canvasdrawPath(mPath, mLinePaint); //绘制线
canvasrestore();
}
canvasrestore();
}
复制代码
13绘制文字
Flutter中绘制文字可有点略坑,我这里简单的封了一个drawText函数用来画文字
记得导入ui库,使用Paragraph进行文字的设置,drawParagraph进行绘制
import 'dart:ui' as ui;
//绘制文字
void drawInfoText(Canvas canvas) {
double r2 = mRadius - 008 mRadius; //下圆半径
for (int i = 0; i < datalength; i++) {
canvassave();
canvasrotate(360 / datalength i / 180 pi + pi);
drawText(canvas, datakeystoList()[i], Offset(-50, r2 - 022 mRadius),
fontSize: mRadius 01);
canvasrestore();
}
}
//绘制文字
drawText(Canvas canvas, String text, Offset offset,
{Color color=Colorsblack,
double maxWith = 100,
double fontSize,
String fontFamily,
TextAlign textAlign=TextAligncenter,
FontWeight fontWeight=FontWeightbold}) {
// 绘制文字
var paragraphBuilder = uiParagraphBuilder(
uiParagraphStyle(
fontFamily: fontFamily,
textAlign: textAlign,
fontSize: fontSize,
fontWeight: fontWeight,
),
);
paragraphBuilderpushStyle(
uiTextStyle(color: color, textBaseline: uiTextBaselinealphabetic));
paragraphBuilderaddText(text);
var paragraph = paragraphBuilderbuild();
paragraphlayout(uiParagraphConstraints(width: maxWith));
canvasdrawParagraph(paragraph, Offset(offsetdx, offsetdy));
}
复制代码
14绘制范围
最后也是最难的一块,你准备好草稿纸了吗
//绘制区域
drawAbility(Canvas canvas, List<double> value) {
double step = mRadius0618 / 6; //每小段的长度
mAbilityPathmoveTo(0, -value[0] / 20 step); //起点
for (int i = 1; i < 6; i++) {
double mark = value[i] / 20;//占几段
mAbilityPathlineTo(
mark step cos(pi / 180 (-30 + 60 (i - 1))),
mark step sin(pi / 180 (-30 + 60 (i - 1))));
}
mAbilityPathclose();
canvasdrawPath(mAbilityPath, mAbilityPaint);
}
复制代码
2动画效果
让外圈转和内圈相反方向转,所以可以让内圈和外圈分成两个组件放在一个Stack里
21:抽离外圈
class OutlinePainter extends CustomPainter {
double mRadius = 100; //外圆半径
Paint mLinePaint; //线画笔
Paint mFillPaint; //填充画笔
OutlinePainter() {
mLinePaint = Paint()
color = Colorsblack
style = PaintingStylestroke
strokeWidth = 0008 mRadius
isAntiAlias = true;
mFillPaint = Paint() //填充画笔
strokeWidth = 005 mRadius
color = Colorsblack
isAntiAlias = true;
}
@override
void paint(Canvas canvas, Size size) {
drawOutCircle(canvas);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
// TODO: implement shouldRepaint
return true;
}
//绘制外圈
void drawOutCircle(Canvas canvas) {
canvassave(); //新建图层
canvasdrawCircle(Offset(0, 0), mRadius, mLinePaint); //圆形的绘制
double r2 = mRadius - 008 mRadius; //下圆半径
canvasdrawCircle(Offset(0, 0), r2, mLinePaint);
for (var i = 00; i < 22; i++) {
//循环画出小黑条
canvassave(); //新建图层
canvasrotate(360 / 22 i / 180 pi); //旋转:注意传入的是弧度(与Android不同)
canvasdrawLine(Offset(0, -mRadius), Offset(0, -r2), mFillPaint); //线的绘制
canvasrestore(); //释放图层
}
canvasrestore(); //释放图层
}
}
复制代码
22:使用动画
这里用Stack进行组件的堆叠
class _AbilityWidgetState extends State<AbilityWidget>
with SingleTickerProviderStateMixin {
var _angle = 00;
AnimationController controller;
Animation<double> animation;
@override
void initState() {
superinitState();
controller = AnimationController(
////创建 Animation对象
duration: const Duration(milliseconds: 2000), //时长
vsync: this);
var tween = Tween(begin: 00, end: 3600); //创建从25到150变化的Animatable对象
animation = tweenanimate(controller); //执行animate方法,生成
animationaddListener(() {
setState(() {
_angle = animationvalue;
});
});
controllerforward();
}
@override
Widget build(BuildContext context) {
var paint = CustomPaint(
painter: AbilityPainter(),
);
var outlinePainter = Transformrotate(
angle: _angle / 180 pi,
child: CustomPaint(
painter: OutlinePainter(),
),
);
var img = Transformrotate(
angle: _angle / 180 pi,
child: Opacity(
opacity: animationvalue / 360 04,
child: ClipOval(
child: Imageasset(
"images/娜美jpg",
width: 200,
height: 200,
fit: BoxFitcover,
),
),
),
);
var center = Transformrotate(
angle: -_angle / 180 pi,
child: Transformscale(
scale: 05 + animationvalue / 360 / 2,
child: SizedBox(
width: 200,
height: 200,
child: paint,
),
));
return Center(
child: Stack(
alignment: Alignmentcenter,
children: <Widget>[img, center, outlinePainter],
),
);
}
}
复制代码
3组件封装
到现在逻辑上没有问题了,剩下的就是对组件的封装,将一些量进行提取
下面就是简单封装了一下,还有很多乱七八糟的没封装,比如颜色,动画效果等。
import 'dart:math';
import 'dart:ui' as ui;
import 'package:flutter/materialdart';
class Ability {
double radius;
int duration;
ImageProvider image;
Map<String,double> data;
Color color;
Ability({thisradius, thisduration, thisimage, thisdata, thiscolor});
}
class AbilityWidget extends StatefulWidget {
AbilityWidget({Key key, thisability}) : super(key: key);
final Ability ability;
@override
_AbilityWidgetState createState() => _AbilityWidgetState();
}
class _AbilityWidgetState extends State<AbilityWidget>
with SingleTickerProviderStateMixin {
var _angle = 00;
AnimationController controller;
Animation<double> animation;
@override
void initState() {
superinitState();
controller = AnimationController(
////创建 Animation对象
duration: Duration(milliseconds: widgetabilityduration), //时长
vsync: this);
var curveTween = CurveTween(curve:Cubic(096, 013, 01, 12));//创建curveTween
var tween=Tween(begin: 00, end: 3600);
animation = tweenanimate(curveTweenanimate(controller));
animationaddListener(() {
setState(() {
_angle = animationvalue;
print(_angle);
});
});
controllerforward();
}
@override
Widget build(BuildContext context) {
var paint = CustomPaint(
painter: AbilityPainter(widgetabilityradius,widgetabilitydata),
);
var outlinePainter = Transformrotate(
angle: _angle / 180 pi,
child: CustomPaint(
painter: OutlinePainter(widgetabilityradius ),
),
);
var img = Transformrotate(
angle: _angle / 180 pi,
child: Opacity(
opacity: animationvalue / 360 04,
child: ClipRRect(
borderRadius: BorderRadiuscircular(widgetabilityradius),
child: Image(
image: widgetabilityimage,
width: widgetabilityradius 2,
height: widgetabilityradius 2,
fit: BoxFitcover,
),
),
),
);
var center = Transformrotate(
angle: -_angle / 180 pi,
child: Transformscale(
scale: 05 + animationvalue / 360 / 2,
child: SizedBox(
width: widgetabilityradius 2,
height: widgetabilityradius 2,
child: paint,
),
));
return Center(
child: Stack(
alignment: Alignmentcenter,
children: <Widget>[img, center, outlinePainter],
),
);
}
}
class OutlinePainter extends CustomPainter {
double _radius; //外圆半径
Paint mLinePaint; //线画笔
Paint mFillPaint; //填充画笔
OutlinePainter(this_radius) {
mLinePaint = Paint()
color = Colorsblack
style = PaintingStylestroke
strokeWidth = 0008 _radius
isAntiAlias = true;
mFillPaint = Paint() //填充画笔
strokeWidth = 005 _radius
color = Colorsblack
isAntiAlias = true;
}
@override
void paint(Canvas canvas, Size size) {
drawOutCircle(canvas);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
// TODO: implement shouldRepaint
return true;
}
//绘制外圈
void drawOutCircle(Canvas canvas) {
canvassave(); //新建图层
canvasdrawCircle(Offset(0, 0), _radius, mLinePaint); //圆形的绘制
double r2 = _radius - 008 _radius; //下圆半径
canvasdrawCircle(Offset(0, 0), r2, mLinePaint);
for (var i = 00; i < 22; i++) {
//循环画出小黑条
canvassave(); //新建图层
canvasrotate(360 / 22 i / 180 pi); //旋转:注意传入的是弧度(与Android不同)
canvasdrawLine(Offset(0, -_radius), Offset(0, -r2), mFillPaint); //线的绘制
canvasrestore(); //释放图层
}
canvasrestore(); //释放图层
}
}
class AbilityPainter extends CustomPainter {
Map<String, double> _data;
double _r; //外圆半径
Paint mLinePaint; //线画笔
Paint mAbilityPaint; //区域画笔
Paint mFillPaint; //填充画笔
Path mLinePath; //短直线路径
Path mAbilityPath; //范围路径
AbilityPainter(this_r, this_data) {
mLinePath = Path();
mAbilityPath = Path();
mLinePaint = Paint()
color = Colorsblack
style = PaintingStylestroke
strokeWidth = 0008 _r
isAntiAlias = true;
mFillPaint = Paint() //填充画笔
strokeWidth = 005 _r
color = Colorsblack
isAntiAlias = true;
mAbilityPaint = Paint()
color = Color(0x8897C5FE)
isAntiAlias = true;
}
@override
void paint(Canvas canvas, Size size) {
//剪切画布
Rect rect = Offsetzero & size;
canvasclipRect(rect);
canvastranslate(_r, _r); //移动坐标系
drawInnerCircle(canvas);
drawInfoText(canvas);
drawAbility(canvas, _datavaluestoList());
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
//绘制内圈圆
drawInnerCircle(Canvas canvas) {
double innerRadius = 0618 _r; //内圆半径
canvasdrawCircle(Offset(0, 0), innerRadius, mLinePaint);
canvassave();
for (var i = 0; i < _datalength; i++) {
//遍历6条线
canvassave();
canvasrotate(360/_datalength itoDouble() / 180 pi); //每次旋转60°
mLinePathmoveTo(0, -innerRadius);
mLinePathrelativeLineTo(0, innerRadius); //线的路径
for (int j = 1; j < _datalength; j++) {
mLinePathmoveTo(-_r 002, innerRadius / _datalength j);
mLinePathrelativeLineTo(_r 002 2, 0);
} //加5条小线
canvasdrawPath(mLinePath, mLinePaint); //绘制线
canvasrestore();
}
canvasrestore();
}
//绘制文字
void drawInfoText(Canvas canvas) {
double r2 = _r - 008 _r; //下圆半径
for (int i = 0; i < _datalength; i++) {
canvassave();
canvasrotate(360 / _datalength i / 180 pi + pi);
drawText(canvas, _datakeystoList()[i], Offset(-50, r2 - 022 _r),
fontSize: _r 01);
canvasrestore();
}
}
//绘制区域
drawAbility(Canvas canvas, List<double> value) {
double step = _r 0618 / _datalength; //每小段的长度
mAbilityPathmoveTo(0, -value[0] / (100/_datalength) step); //起点
for (int i = 1; i < _datalength; i++) {
double mark = value[i] / (100/_datalength);
var deg=pi/180(360/_datalength i - 90);
mAbilityPathlineTo(mark step cos(deg), mark step sin(deg));
}
mAbilityPathclose();
canvasdrawPath(mAbilityPath, mAbilityPaint);
}
//绘制文字
drawText(Canvas canvas, String text, Offset offset,
{Color color = Colorsblack,
double maxWith = 100,
double fontSize,
String fontFamily,
TextAlign textAlign = TextAligncenter,
FontWeight fontWeight = FontWeightbold}) {
// 绘制文字
var paragraphBuilder = uiParagraphBuilder(
uiParagraphStyle(
fontFamily: fontFamily,
textAlign: textAlign,
fontSize: fontSize,
fontWeight: fontWeight,
),
);
paragraphBuilderpushStyle(
uiTextStyle(color: color, textBaseline: uiTextBaselinealphabetic));
paragraphBuilderaddText(text);
var paragraph = paragraphBuilderbuild();
paragraphlayout(uiParagraphConstraints(width: maxWith));
canvasdrawParagraph(paragraph, Offset(offsetdx, offsetdy));
}
}。
比较容易, 但你要熟悉以下内容:
1。 扩展标准的View,实现其onDraw方法
public Paint paint=new Paint (PaintANTI_ALIAS_FLAG);
protected void onDraw(Canvas canvas) {}
2。熟悉paint和canvas的用法
3 在onDraw方法中画多边形,Android的多边形是以Path路径来描述的。
3。熟悉Path路径的用法:
以下代码画一个箭头
Path mPath=new Path();
mPathmoveTo(0, -50);
mPathlineTo(-20, 60);
mPathlineTo(0, 50);
mPathlineTo(20, 60);
mPathclose();
最后:利用canvas把path画出来: canvasdrawPath(mPath)
另外path还有其它方法可以增加一个矩形或弧形进去。
如果要填充就把paint的style改成填充形,不然就是描边形。
path最后一句一定要封闭,即mPathclose();
祝学习愉快。 有空可看看sdk中关于Path的详细说明。 我只是告诉你一个大概,具体你需自己体会。