HarmonyOS鸿蒙Next中基于Canvas、Image组件等实现对个人头像处理以及群头像生成实现
HarmonyOS鸿蒙Next中基于Canvas、Image组件等实现对个人头像处理以及群头像生成实现 场景一:调用系统相机拍照,从系统相册选择图片,根据圆形遮罩,裁剪生成个人头像。
场景一实现方案:
-
创建图片选择器photoViewPicker,设置选择模式为图片,数量最大为1,调用photoViewPicker,将选择的图片以uri形式,存储到cropModel里面,并设置取景框宽度和宽高比。
-
以画布为中心,使用canvas中API的this.context.arc绘制圆形取景框
-
添加拖动手势.gesture(gesturegroup),panGesture(onActionStart,onActionUpdate,onActionEnd)
-
对取景框对图片校准,若拖动缩放图片过程中,拖拽动作停止时,缩放图片太小;未占满取景框时,则将图片缩放到和取景框一样宽度,调整图片和取景框在一个中心点上
-
根据cropModel存储的uri路径,获取图片源,根据生成的XY坐标和size,使用api image.Region获取图片对应的PixelMap
各步骤代码实现:
创建photoViewPicker,选择图片,并以uri形式,存储到cropModel。
// 弹出图片选择器方法
async openPicker() {
try {
// 设置图片选择器选项
const photoSelectOptions = new picker.PhotoSelectOptions();
// 限制只能选择一张图片
photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
photoSelectOptions.maxSelectNumber = 1;
// 创建并实例化图片选择器
const photoViewPicker = new picker.PhotoViewPicker();
// 选择图片并获取图片URI
let uris: picker.PhotoSelectResult = await photoViewPicker.select(photoSelectOptions);
if (!uris || uris.photoUris.length === 0) return;
// 获取选中图片的第一张URI
let uri: string = uris.photoUris[0];
this.model.setImage(uri)
.setFrameWidth(1000)
.setFrameRatio(1);
} catch (e) {
console.error('openPicker', JSON.stringify(e));
}
}
handleFileSelection(event: MyEvent) {
const PhotoSelectOptions = new picker.PhotoSelectOptions();
PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
PhotoSelectOptions.maxSelectNumber = 1;
const photoPicker = new picker.PhotoViewPicker();
photoPicker.select(PhotoSelectOptions)
.then((PhotoSelectResult) => {
if (PhotoSelectResult.photoUris.length === 0) {
console.warn('No image selected.');
return;
}
const srcUri = PhotoSelectResult.photoUris[0];
this.model.setImage(srcUri)
.setFrameWidth(1000)
.setFrameRatio(1);
})
.catch((selectError: object) => {
console.error('Failed to invoke photo picker:', JSON.stringify(selectError));
});
return true;
}
使用画布进行圆形取景框的绘制。
Canvas(this.context).width('100%').height('100%')
.backgroundColor(Color.Transparent)
.onReady(() => {
if (this.context == null) {
return
}
let height = this.context.height
let width = this.context.width
this.context.fillStyle= this.model.maskColor;
this.context.fillRect(0, 0, width, height)
// 计算圆形的中心点和半径
let centerX = width / 2;
let centerY = height / 2;
let minDimension = Math.min(width, height);
let frameRadiusInVp = (minDimension - px2vp(this.model.frameWidth)) / 2; // 减去边框宽度
// 把中间的取景框透出来
this.context.globalCompositeOperation = 'destination-out'
this.context.fillStyle = 'white'
let frameWidthInVp = px2vp(this.model.frameWidth);
let frameHeightInVp = px2vp(this.model.getFrameHeight());
let x = (width - px2vp(this.model.frameWidth)) / 2;
let y = (height - px2vp(this.model.getFrameHeight())) / 2;
this.context.beginPath();
this.context.arc(centerX, centerY, px2vp(this.model.frameWidth/2), 0, 2 * Math.PI);
this.context.fill();
// 设置综合操作模式为源覆盖,以便在现有图形上添加新的图形
this.context.globalCompositeOperation = 'source-over';
// 设置描边颜色
this.context.strokeStyle = this.model.strokeColor;
// 计算圆形的半径,这里我们取正方形边框的较短边的一半作为半径
let radius = Math.min(frameWidthInVp, frameHeightInVp) / 2;
// 开始绘制路径
this.context.beginPath();
// 使用 arc 方法绘制圆形
this.context.arc(centerX, centerY, radius, 0, 2 * Math.PI);
// 关闭路径
this.context.closePath();
// 描绘圆形边框
this.context.lineWidth = 1; // 边框宽度
this.context.stroke();
})
添加拖拽手势,调整获取图片的内容。
.
gesture(
GestureGroup(GestureMode.Parallel,
// 拖动手势
PanGesture({})
.onActionStart(() => {
hilog.info(0, "CropView", "Pan gesture start");
this.startOffsetX = this.model.offsetX;
this.startOffsetY = this.model.offsetY;
})
.onActionUpdate((event:GestureEvent) => {
hilog.info(0, "CropView", `Pan gesture update: ${JSON.stringify(event)}`);
if (event) {
if (this.model.panEnabled) {
let distanceX: number = this.startOffsetX + vp2px(event.offsetX) / this.model.scale;
let distanceY: number = this.startOffsetY + vp2px(event.offsetY) / this.model.scale;
this.model.offsetX = distanceX;
this.model.offsetY = distanceY;
this.updateMatrix()
}
}
})
.onActionEnd(() => {
hilog.info(0, "CropView", "Pan gesture end");
this.checkImageAdapt();
}),
// 缩放手势处理
PinchGesture({ fingers: 2 })
.onActionStart(() => {
this.tempScale = this.model.scale
})
.onActionUpdate((event) => {
if (event) {
if (!this.model.zoomEnabled) return;
this.zoomTo(this.tempScale * event.scale);
}
})
.onActionEnd(() => {
this.checkImageAdapt();
})
)
)
拖拽结束对取景框校准。
/**
* 检查手势操作后,图片是否填满取景框,没填满则进行调整
*/
private checkImageAdapt() {
let offsetX = this.model.offsetX;
let offsetY = this.model.offsetY;
let scale = this.model.scale;
hilog.info(0, "CropView", `offsetX: ${offsetX}, offsetY: ${offsetY}, scale: ${scale}`)
// 图片适配控件的时候也进行了缩放,计算出这个缩放比例
let widthScale = this.model.componentWidth / this.model.imageWidth;
let heightScale = this.model.componentHeight / this.model.imageHeight;
let adaptScale = Math.min(widthScale, heightScale);
hilog.info(0, "CropView", `Image scale ${adaptScale} while attaching the component[${this.model.componentWidth}, ${this.model.componentHeight}]`)
// 经过两次缩放(适配控件、手势)后,图片的实际显示大小
let showWidth = this.model.imageWidth * adaptScale * this.model.scale;
let showHeight = this.model.imageHeight * adaptScale * this.model.scale;
let imageX = (this.model.componentWidth - showWidth) / 2;
let imageY = (this.model.componentHeight - showHeight) / 2;
hilog.info(0, "CropView", `Image left top is (${imageX}, ${imageY})`)
// 取景框的左上角坐标
let frameX = (this.model.componentWidth - this.model.frameWidth) / 2;
let frameY = (this.model.componentHeight - this.model.getFrameHeight()) / 2;
// 图片左上角坐标
let showX = imageX + offsetX * scale;
let showY = imageY + offsetY * scale;
hilog.info(0, "CropView", `Image show at (${showX}, ${showY})`)
if(this.model.frameWidth > showWidth || this.model.getFrameHeight() > showHeight) { // 图片缩放后,大小不足以填满取景框
let xScale = this.model.frameWidth / showWidth;
let yScale = this.model.getFrameHeight() / showHeight;
let newScale = Math.max(xScale, yScale);
this.model.scale = this.model.scale * newScale;
showX *= newScale;
showY *= newScale;
}
// 调整x轴方向位置,使图像填满取景框
if(showX > frameX) {
showX = frameX;
} else if(showX + showWidth < frameX + this.model.frameWidth) {
showX = frameX + this.model.frameWidth - showWidth;
}
// 调整y轴方向位置,使图像填满取景框
if(showY > frameY) {
showY = frameY;
} else if(showY + showHeight < frameY + this.model.getFrameHeight()) {
showY = frameY + this.model.getFrameHeight() - showHeight;
}
this.model.offsetX = (showX - imageX) / scale;
this.model.offsetY = (showY - imageY) / scale;
this.updateMatrix();
}
根据取景框的内缩放图片的位置大小,生成新pixelMap数据。
public async crop(format: image.PixelMapFormat) : Promise<image.PixelMap> {
if(!this.src || this.src == '') {
throw new Error('Please set src first');
}
if(this.imageWidth == 0 || this.imageHeight == 0) {
throw new Error('The image is not loaded');
}
// 图片适配控件的时候也进行了缩放,计算出这个缩放比例
let widthScale = this.componentWidth / this.imageWidth;
let heightScale = this.componentHeight / this.imageHeight;
let adaptScale = Math.min(widthScale, heightScale);
// 经过两次缩放(适配控件、手势)后,图片的实际显示大小
let totalScale = adaptScale * this.scale;
let showWidth = this.imageWidth * totalScale;
let showHeight = this.imageHeight * totalScale;
let imageX = (this.componentWidth - showWidth) / 2;
let imageY = (this.componentHeight - showHeight) / 2;
// 取景框的左上角坐标
let frameX = (this.componentWidth - this.frameWidth) / 2;
let frameY = (this.componentHeight - this.getFrameHeight()) / 2;
// 图片左上角坐标
let showX = imageX + this.offsetX * this.scale;
let showY = imageY + this.offsetY * this.scale;
let x = (frameX - showX) / totalScale;
let y = (frameY - showY) / totalScale;
let file = fs.openSync(this.src, fs.OpenMode.READ_ONLY)
let imageSource : image.ImageSource = image.createImageSource(file.fd);
let decodingOptions : image.DecodingOptions = {
editable: true,
desiredPixelFormat: image.PixelMapFormat.BGRA_8888,
}
// 创建pixelMap
let pm = await imageSource.createPixelMap(decodingOptions);
let cp = await this.copyPixelMap(pm);
pm.release();
let region: image.Region = { x: x, y: y, size: { width: this.frameWidth / totalScale, height: this.getFrameHeight() / totalScale } };
cp.cropSync(region);
return cp;
}
async copyPixelMap(pm: PixelMap): Promise<PixelMap> {
const imageInfo: image.ImageInfo = await pm.getImageInfo();
const buffer: ArrayBuffer = new ArrayBuffer(pm.getPixelBytesNumber());
// TODO 知识点:通过readPixelsToBuffer实现PixelMap的深拷贝,其中readPixelsToBuffer输出为BGRA_8888
await pm.readPixelsToBuffer(buffer);
// TODO 知识点:readPixelsToBuffer输出为BGRA_8888,此处createPixelMap需转为RGBA_8888
const opts: image.InitializationOptions = {
editable: true,
pixelFormat: image.PixelMapFormat.RGBA_8888,
size: { height: imageInfo.size.height, width: imageInfo.size.width }
};
return image.createPixelMap(buffer, opts);
}
更多关于HarmonyOS鸿蒙Next中基于Canvas、Image组件等实现对个人头像处理以及群头像生成实现的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,可以通过Canvas和Image组件来实现对个人头像的处理以及群头像的生成。Canvas组件提供了强大的绘图能力,开发者可以在Canvas上绘制各种图形、图像,并进行图像处理操作。Image组件则用于显示图像,并且支持图像的缩放、裁剪等操作。
对于个人头像处理,开发者可以使用Canvas组件对头像进行绘制和处理。例如,可以使用Canvas的drawImage方法将个人头像绘制到Canvas上,然后通过Canvas的API对图像进行裁剪、缩放、旋转等操作。处理后的图像可以通过Canvas的toDataURL方法转换为Base64编码的图片数据,或者直接通过Image组件显示出来。
对于群头像生成,开发者可以通过Canvas组件将多个头像合并为一个群头像。具体步骤包括:首先,使用Canvas的drawImage方法将每个成员的头像绘制到Canvas的不同位置;然后,可以通过Canvas的API对图像进行布局调整、缩放等操作,确保群头像的整体效果;最后,将生成的群头像通过Canvas的toDataURL方法转换为Base64编码的图片数据,或者直接通过Image组件显示出来。
在HarmonyOS鸿蒙Next中,Canvas和Image组件的结合使用,使得头像处理和群头像生成变得更加灵活和高效。开发者可以根据具体需求,利用这些组件实现丰富的图像处理功能。
更多关于HarmonyOS鸿蒙Next中基于Canvas、Image组件等实现对个人头像处理以及群头像生成实现的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,通过Canvas和Image组件可以实现个人头像处理及群头像生成。首先,使用Image组件加载个人头像,并通过Canvas的drawImage方法进行裁剪、缩放等处理。对于群头像生成,可以将多个头像按特定布局排列在Canvas上,使用drawImage依次绘制每个头像,并通过调整坐标和尺寸实现自定义布局。最后,使用Canvas的toDataURL方法将合成图像导出为Base64或文件格式。