开发者在绘制圆角矩形时,可能会遇到以下几个场景:
interface RectSize {
width: number,
height: number
}
interface RectPosition {
x: number,
y: number
}
interface PositionData {
postion: RectPosition,
size: RectSize,
}
@Entry
@Component
struct CanvasRadiusRect {
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
private positionList: PositionData[] = [
{
postion: { x: 8, y: 50 },
size: { width: 360, height: 185 }
}
];
drawRect(rectPosition: RectPosition, rectSize: RectSize, radius: number = 10) {
// 圆角弧度
// 左上角坐标x
let x = rectPosition.x;
// 左上角坐标y
let y = rectPosition.y;
// 矩形宽
let width = rectSize.width;
// 矩形高
let height = rectSize.height;
this.context.beginPath();
this.context.moveTo(0, 0);
this.context.lineTo(0, this.context.height);
this.context.lineTo(this.context.width, this.context.height);
this.context.lineTo(this.context.width, 0);
this.context.lineTo(0, 0);
this.context.moveTo(x + radius, y);
this.context.lineTo(x + width - radius, y);
this.context.arcTo(x + width, y, x + width, y + radius, radius);
this.context.lineTo(x + width, y + height - radius);
this.context.arcTo(x + width, y + height, x + width - radius, y + height, radius);
this.context.lineTo(x + radius, y + height);
this.context.arcTo(x, y + height, x, y + height - radius, radius);
this.context.lineTo(x, y + radius);
this.context.arcTo(x, y, x + radius, y, radius);
this.context.fillStyle = '#aa6ad4d0';
this.context.fill();
this.context.closePath();
}
build() {
Column() {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#00000000')
.onReady(() => {
this.drawRect(this.positionList[0]?.postion, this.positionList[0]?.size);
});
}
.height('100%')
.width('100%');
}
} @Entry
@Component
struct PolygonExample {
build() {
Column({ space: 10 }) {
// 在100*100的矩形框中绘制一个四边形,起点(0,0),经过(0,100)和(100,100),终点(100,0)。
Polygon()
.width(100)
.height(100)
.points([[0, 0], [0, 100], [100, 100], [100, 0]])
.strokeWidth(10)
.stroke('#99000000')
.fill('#99000000')
.strokeLineJoin(LineJoinStyle.Round); // 设置边框拐角绘制样式
}
.width('100%')
.margin({ top: 10 });
}
} 五种方案对比:
方案 | 优缺点 | 适用场景 |
|---|---|---|
方案一 | 使用较复杂,支持通过路径操作实现复杂图形的构建与处理。 | 适用于对图形定制化程度较高,或需要动态更新的复杂应用场景。 |
方案二 | 使用便捷,但可定制化程度有限。 | 适用于对图形复杂度要求较低的简单绘制场景。 |
方案三 | 依赖CPU进行绘制,绘制速度相对较慢,因此对绘制性能有较高要求的场景应避免使用离屏绘制。 | 适用于非频繁更新的静态内容。 |
方案四 | 代码结构简洁,但无法动态计算路径坐标,难以实现复杂图形;渲染引擎直接处理性能较高。 | 适用于对图形复杂度要求不高的简单绘制场景。 |
方案五 | 使用较复杂,性能较高,但需注意内存管理。 | 适用于对高性能有需求,或需要与Native代码交互的场景。 |
import { Point } from '@kit.TestKit';
@Entry
@Component
struct CanvasRadiusText {
private readonly settings: RenderingContextSettings = new RenderingContextSettings(true);
private readonly ctx: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
center: Point = { x: 200, y: 200 };
backSize: Size = { width: 200, height: 200 };
private drawRoundRect(center: Point, size: Size, radius: number) {
const x = center.x - size.width / 2;
const y = center.y - size.height / 2;
let path = new Path2D();
path.moveTo(x + radius, y);
path.arcTo(x + size.width, y, x + size.width, y + radius, radius);
path.arcTo(x + size.width, y + size.height, x + size.width - radius, y + size.height, radius);
path.arcTo(x, y + size.height, x, y + radius, radius);
path.arcTo(x, y, x + radius, y, radius);
path.closePath();
this.ctx.fillStyle = '#0097D4';
this.ctx.fill(path);
}
private drawText() {
let str = 'hello world';
this.ctx.font = '30vp';
this.ctx.textAlign = 'center';
this.ctx.textBaseline = 'middle';
let metrics = this.ctx.measureText(str);
// 绘制文字显示区域
this.ctx.fillStyle = Color.Green;
this.ctx.fillRect(this.center.x - metrics.width / 2, this.center.y - metrics.height / 2, metrics.width,
metrics.height);
// 把文字绘制到背景正中心
this.ctx.fillStyle = Color.Black;
this.ctx.fillText(str, this.center.x, this.center.y);
}
build() {
Stack() {
Canvas(this.ctx)
.height('100%')
.width('100%')
.onReady(() => {
this.drawRoundRect(this.center, this.backSize, 20);
this.drawText();
})
.backgroundColor('#eee');
}.height('100%').width('100%');
}
} @Entry
@Component
struct CanvasMaskDemo {
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Row() {
Column() {
Stack() {
Image($r('app.media.startIcon')).height(300); // 此处仅为样例,请开发者替换为可用图片
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#00000000')
.onReady(() => {
// 圆角弧度
let radius = 10;
// 左上角坐标x
let x = 100;
// 左上角坐标y
let y = 350;
// 矩形宽
let width = 100;
// 矩形高
let height = 40;
this.context.beginPath();
this.context.moveTo(0, 0);
this.context.lineTo(0, this.context.height);
this.context.lineTo(this.context.width, this.context.height);
this.context.lineTo(this.context.width, 0);
this.context.lineTo(0, 0);
this.context.moveTo(x + radius, y);
this.context.lineTo(x + width - radius, y);
this.context.arcTo(x + width, y, x + width, y + radius, radius);
this.context.lineTo(x + width, y + height - radius);
this.context.arcTo(x + width, y + height, x + width - radius, y + height, radius);
this.context.lineTo(x + radius, y + height);
this.context.arcTo(x, y + height, x, y + height - radius, radius);
this.context.lineTo(x, y + radius);
this.context.arcTo(x, y, x + radius, y, radius);
this.context.fillStyle = '#aa000000';
this.context.fill();
this.context.closePath();
});
}.width('100%')
.height('100%');
}
.width('100%');
}
.height('100%');
}
} @Entry
@Component
struct PKBarCanvas {
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
// ImageBitmap需使能相关开关:模块的build-profile.json5中buildOption>resOptions>copyCodeResource>enable设置为true。
private avatarImage: ImageBitmap = new ImageBitmap('common/images/startIcon.png');
build() {
Column() {
Canvas(this.context)
.width(350)
.height(60)
.onReady(() => {
this.drawPKBar();
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
.backgroundColor(0x222222)
}
drawPKBar() {
const ctx = this.context;
const totalWidth = 350;
const totalHeight = 60;
const cornerRadius = 15;
const slopeOffset = 12;
const middleGap = 10;
// 【新增】左边占比(0.6表示左边占60%,右边占40%,可调整)
const leftWidthRatio = 0.6;
// 根据比例计算左右分割线的X坐标
const splitX = totalWidth * leftWidthRatio;
// ————————————————1.绘制PK条底色————————————————
ctx.clearRect(0, 0, totalWidth, totalHeight);
// 左边底色(变长)
ctx.beginPath();
ctx.moveTo(cornerRadius, 0);
// 上边线终点改为splitX
ctx.lineTo(splitX - (middleGap / 2) + slopeOffset, 0);
// 斜边底端X坐标改为splitX
ctx.lineTo(splitX - (middleGap / 2) - slopeOffset, totalHeight);
ctx.lineTo(cornerRadius, totalHeight);
ctx.arcTo(0, totalHeight, 0, totalHeight - cornerRadius, cornerRadius);
ctx.lineTo(0, cornerRadius);
ctx.arcTo(0, 0, cornerRadius, 0, cornerRadius);
ctx.closePath();
// 左边渐变终点也改为splitX
const leftGradient = ctx.createLinearGradient(0, 0, splitX, 0);
leftGradient.addColorStop(0, '#FF416C');
leftGradient.addColorStop(1, '#FF4B2B');
ctx.fillStyle = leftGradient;
ctx.fill();
// 右边底色(变短)
ctx.beginPath();
// 起点改为splitX
ctx.moveTo(splitX + (middleGap / 2) + slopeOffset, 0);
ctx.lineTo(totalWidth - cornerRadius, 0);
ctx.arcTo(totalWidth, 0, totalWidth, cornerRadius, cornerRadius);
ctx.lineTo(totalWidth, totalHeight - cornerRadius);
ctx.arcTo(totalWidth, totalHeight, totalWidth - cornerRadius, totalHeight, cornerRadius);
// 下边线终点改为splitX
ctx.lineTo(splitX + (middleGap / 2) - slopeOffset, totalHeight);
ctx.lineTo(splitX + (middleGap / 2) + slopeOffset, 0);
ctx.closePath();
// 右边渐变起点也改为splitX
const rightGradient = ctx.createLinearGradient(totalWidth, 0, splitX, 0);
rightGradient.addColorStop(0, '#00F260');
rightGradient.addColorStop(1, '#0575E6');
ctx.fillStyle = rightGradient;
ctx.fill();
// ————————————————2.绘制头像和分数————————————————
const avatarRadius = 18;
const textMargin = 10;
const fontSize = 20;
const leftScore = '96';
const rightScore = '86';
// 左边头像和分数(位置不变,依然在最左侧)
ctx.save();
const leftAvatarX = cornerRadius + 5 + avatarRadius;
const leftAvatarY = totalHeight / 2;
ctx.beginPath();
ctx.arc(leftAvatarX, leftAvatarY, avatarRadius, 0, Math.PI * 2);
ctx.clip();
ctx.drawImage(
this.avatarImage,
leftAvatarX - avatarRadius,
leftAvatarY - avatarRadius,
avatarRadius * 2,
avatarRadius * 2
);
ctx.restore();
ctx.font = `bold ${fontSize}vp sans-serif`;
ctx.fillStyle = '#FFFFFF';
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
ctx.fillText(leftScore, leftAvatarX + avatarRadius + textMargin, leftAvatarY);
// 右边头像和分数(位置不变,依然在最右侧)
ctx.save();
const rightAvatarX = totalWidth - cornerRadius - 5 - avatarRadius;
const rightAvatarY = totalHeight / 2;
ctx.beginPath();
ctx.arc(rightAvatarX, rightAvatarY, avatarRadius, 0, Math.PI * 2);
ctx.clip();
ctx.drawImage(
this.avatarImage,
rightAvatarX - avatarRadius,
rightAvatarY - avatarRadius,
avatarRadius * 2,
avatarRadius * 2
);
ctx.restore();
ctx.textAlign = 'right';
ctx.fillText(rightScore, rightAvatarX - avatarRadius - textMargin, rightAvatarY);
}
}