绘图
绘图中常用到Canvas来进行绘图,Drawing同样可以用来绘图,但相对来说偏向底层,一般使用的还是Canvas,绘图相对来说较难画出美观的图形,同样可以使用鸿蒙的第三方库进行绘图。下文将着重写Canvas绘图。
创建画布
通过创建画布然后在画布里进行绘图。
@Entry
@Component
struct LineCapExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
//Flex{(direaction: 布局方向, alignItems: 子项在交叉轴对齐方式, justifyContent: 主轴对齐方式)}
//一般不会更改Flex里的几个参数,直接用就可以
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
//创建一个Canvas元素
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
//画图代码位置
})
}
.width('100%')
.height('100%')
}
}
确定线条样式
.onReady(() => {
this.context.strokeStyle = '#FFFF00'; // 描边颜色,线条,描边矩形等的颜色
this.context.lineWidth = 2; //线条宽度
this.context.fillStyle = '#FFFFFF'; // 填充色,可以规定文本,矩形的填充颜色
this.context.font = '50px Arial'; //文本大小
})
直线
.onReady(() =>{
//新创建一个路径,注意,一个路径会首尾相连,画不同的图要有不同的路径
this.context.beginPath()
//moveTo只用一个,后续都可以使用lineTO
this.context.moveTo(20,60) //起始点的坐标
this.context.lineTo(30,80) //从起始点到这个点的直线
this.context.lineTo(40,100) //从上一个点到这个点的直线
//实际绘制,使用完后可以创建新的路径
this.context.stroke()
})
矩形
.onReady(() => {
this.context.beginPath()
// 绘制填充矩形
context.fillStyle = 'blue'; // 设置填充颜色
context.fillRect(10, 10, 100, 50); // 绘制一个从(10,10)开始,宽100px,高50px的蓝色填充矩形 this.context.stroke()
// 绘制描边矩形
this.context.beginPath()
context.strokeStyle = 'red'; // 设置描边颜色
context.lineWidth = 2; // 设置描边宽度
context.strokeRect(120, 10, 100, 50); // 绘制一个从(120,10)开始,宽100px,高50px的红色描边矩形
this.context.stroke()
})
圆形
.onReady(() => {
// 假设context是你的CanvasRenderingContext2D实例
// 绘制圆形
this.context.beginPath(); // 开始一个新路径
this.context.arc(175, 50, 50, 0, 2 * Math.PI); // 绘制一个圆心在(175,50),半径为50px的圆
// 填充圆形
this.context.fillStyle = 'green';
this.context.fill();
// 或者描边圆形
this.context.beginPath(); // 需要重新开始一个新路径来描边,因为fill()会结束当前路径
this.context.arc(175, 100, 50, 0, 2 * Math.PI); // 再次绘制相同的圆
this.context.strokeStyle = 'black';
this.context.lineWidth = 2;
this.context.stroke();
})
二次贝塞尔曲线
.onReady(() =>{
this.context.beginPath()
this.context.moveTo(20, 20)//曲线开始点
//this.context.quadraticCurveTo(x1,y1,x2,y2)中第两个数值为曲线会绕过的点,用来确定曲线的弯曲程度和弯曲方向,后两个数值为图像结束点。可以理解为moveTo中的起始点和这里的终点的一条线会绕过这里的绕过点。
this.context.quadraticCurveTo(100, 200, 200, 20)
this.context.stroke()
})
在曲线指定位置画圆圈
.onReady(() =>{
const startX = 20, startY = 20;
const cpX = 100, cpY = 100;
const endX = 200, endY = 20;
// 选择一个t值
const t = 1; // 例如,在曲线的中点
// 计算曲线上的点
const x = Math.pow(1-t, 2) * startX + 2 * t * (1-t) * cpX + Math.pow(t, 2) * endX;
const y = Math.pow(1-t, 2) * startY + 2 * t * (1-t) * cpY + Math.pow(t, 2) * endY;
// 绘制曲线
this.context.beginPath();
this.context.moveTo(startX, startY);
this.context.quadraticCurveTo(cpX, cpY, endX, endY);
this.context.stroke();
this.context.moveTo(20,60)
this.context.
// 在计算出的点上画圆
this.context.beginPath();
this.context.arc(x, y, 5, 0, 2 * Math.PI); // 半径为5的圆
this.context.fill();
})