/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//[Start gridExample_start]
import { image } from '@kit.ImageKit';
@Entry
@Component
struct GridEts {
@State pixmap: image.PixelMap | undefined = undefined;
@State numbers: number[] = [];
@State isSelectedGrid: boolean[] = [];
@State previewData: DragItemInfo[] = [];
@State numberBadge: number = 0;
@Styles
normalStyles(): void {
.opacity(1.0);
}
@Styles
selectStyles(): void {
.opacity(0.4);
}
onPageShow(): void {
let i: number = 0;
for(i = 0; i < 100; i++) {
this.numbers.push(i);
this.isSelectedGrid.push(false);
this.previewData.push({});
}
}
@Builder
RandomBuilder(idx: number) {
Column()
.backgroundColor(Color.Blue)
.width(50)
.height(50)
.opacity(1.0)
}
build() {
Column({ space: 5 }) {
Grid() {
ForEach(this.numbers, (idx: number) => {
GridItem() {
Column()
.backgroundColor(Color.Blue)
.width(50)
.height(50)
.opacity(1.0)
.id('grid' + idx)
}
.dragPreview(this.previewData[idx])
.selectable(true)
.selected(this.isSelectedGrid[idx])
// 设置多选显示效果
.stateStyles({
normal: this.normalStyles,
selected: this.selectStyles
})
.onClick(() => {
this.isSelectedGrid[idx] = !this.isSelectedGrid[idx];
if (this.isSelectedGrid[idx]) {
this.numberBadge++;
let gridItemName = 'grid' + idx;
// 选中状态下提前调用componentSnapshot中的get接口获取pixmap
this.getUIContext().getComponentSnapshot().get(gridItemName, (error: Error, pixmap: image.PixelMap) => {
this.pixmap = pixmap;
this.previewData[idx] = {
pixelMap: this.pixmap
};
});
} else {
this.numberBadge--;
}
})
// 使能多选拖拽,右上角数量角标需要应用设置numberBadge参数
.dragPreviewOptions({ numberBadge: this.numberBadge },
{ isMultiSelectionEnabled: true, defaultAnimationBeforeLifting: true })
.onDragStart(() => {
})
}, (idx: string) => idx)
}
.columnsTemplate('1fr 1fr 1fr 1fr 1fr')
.columnsGap(5)
.rowsGap(10)
.backgroundColor(0xFAEEE0)
}.width('100%').margin({ top: 5 })
}
}
//[End gridExample_start]