1、UniMp下载、解密、日志上报
2、适配三键
This commit is contained in:
Elemt 2026-11-03 11:56:48 +08:00
parent 643a826058
commit b173924f39
19 changed files with 350 additions and 64 deletions

View File

@ -43,12 +43,12 @@
"arkOptions": {
"buildProfileFields": {
"CHANNEL": "harmony",
"BUILD_TIME": "2611021826"
"BUILD_TIME": "2611031154"
}
}
},
"output": {
"artifactName": "rabbit_harmony_debug_v1.0.1_2611021826"
"artifactName": "rabbit_harmony_debug_v1.0.1_2611031154"
}
}
],

View File

@ -6,7 +6,7 @@ export const BUILD_MODE_NAME = 'debug';
export const DEBUG = true;
export const TARGET_NAME = 'default';
export const CHANNEL = 'harmony';
export const BUILD_TIME = '2611021826';
export const BUILD_TIME = '2611031154';
/**
* BuildProfile Class is used only for compatibility purposes.

View File

@ -0,0 +1,15 @@
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { hiAppEvent } from '@kit.PerformanceAnalysisKit';
import { init } from '@dcloudio/uni-app-runtime';
export function initUniMpRuntime(ability: UIAbility, stage: window.WindowStage, debug: boolean): void {
try {
init(ability, stage, { debug });
} finally {
// uni-app-runtime 5.14 在 init 中同步注册此监听器。历史 APP_CRASH 随后异步投递时,
// uni-crash 会在尚无 currentMP 的宿主页面调用 uni.getStorageSync,导致启动循环崩溃。
// 只关闭这个 SDK 监听器;系统崩溃日志及其他监听器仍保留。SDK 升级后需重新核验。
hiAppEvent.removeWatcher({ name: 'uniAppCrashWatcher' });
}
}

View File

@ -1,4 +1,5 @@
import { isExistsUniMP, openUniMP, UniMP } from '@dcloudio/uni-app-runtime';
import { getNavigationInsets } from './WindowSafeArea';
import { AESDecrypt, PLATFORM, RELEASE_BASE_URL, Signature, TOKEN, TOKEN_LOGIN, USER_PROFILE } from '../constants/AppConstants';
import { ToastUtils } from '../dialog/ToastUtils';
import { UniVersionEntity, TradeData, UniIconEntity, UserProfile } from '../viewmodel/DataBean';
@ -238,7 +239,7 @@ async function uniMpConfig(context: UIContext): Promise<Record<string, string>>
const bundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
let safeBottom = 0;
try {
safeBottom = Math.max(0, Math.round(context.px2vp(AppUtil.getNavigationIndicatorHeight())));
safeBottom = Math.max(0, Math.ceil(context.px2vp(getNavigationInsets(AppUtil.getMainWindow()).bottom)));
} catch (_) {
// 无导航指示条或窗口尚未就绪时仍传有效值,避免旧 WGT 在 onLaunch 中读取 undefined。
}

View File

@ -6,7 +6,7 @@ import { Logger } from './Logger';
/** 修复旧 WGT 在鸿蒙启动时读取 plus.os.name 等缺失元数据导致的白屏。 */
export class UniMpRuntimeCompat {
static readonly MARKER: string = '/* rabbit-unimp-harmony-compat:v3 */';
static readonly MARKER: string = '/* rabbit-unimp-harmony-compat:v6 */';
static async prepare(context: common.Context, appId: string): Promise<void> {
const servicePath = getUniMPRunPath(appId) + '/www/app-service.js';
@ -15,7 +15,10 @@ export class UniMpRuntimeCompat {
return;
}
if (source.startsWith('/* rabbit-unimp-harmony-compat:v1 */') ||
source.startsWith('/* rabbit-unimp-harmony-compat:v2 */')) {
source.startsWith('/* rabbit-unimp-harmony-compat:v2 */') ||
source.startsWith('/* rabbit-unimp-harmony-compat:v3 */') ||
source.startsWith('/* rabbit-unimp-harmony-compat:v4 */') ||
source.startsWith('/* rabbit-unimp-harmony-compat:v5 */')) {
const endMarker = '/* end-rabbit-unimp-harmony-compat */';
const end = source.indexOf(endMarker);
if (end < 0) {

View File

@ -0,0 +1,156 @@
import { window } from '@kit.ArkUI';
import { common } from '@kit.AbilityKit';
import { settings } from '@kit.BasicServicesKit';
import { Logger } from './Logger';
export interface NavigationInsets {
left: number;
right: number;
bottom: number;
}
// 传统三键导航属于 TYPE_SYSTEM,手势导航属于 TYPE_NAVIGATION_INDICATOR。
// 两类区域可能重叠,取最大值,不能累加;返回值单位为 px。
export function getNavigationInsets(mainWindow: window.Window): NavigationInsets {
const systemArea = mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
const navigationArea = mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
return {
left: Math.max(0, systemArea.leftRect.width, navigationArea.leftRect.width),
right: Math.max(0, systemArea.rightRect.width, navigationArea.rightRect.width),
bottom: Math.max(0, systemArea.bottomRect.height, navigationArea.bottomRect.height)
};
}
const FLOAT_NAVIGATION_KEY: string = 'float_navigation_info';
interface FloatingNavigationInfo {
showType: number;
region: number[];
}
// 悬浮三键在部分系统版本不计入 TYPE_SYSTEM;region 是屏幕坐标,单位 px。
export function getFloatingNavigationInsets(value: string, bounds: window.Rect): NavigationInsets {
const result: NavigationInsets = { left: 0, right: 0, bottom: 0 };
try {
const info = JSON.parse(value) as FloatingNavigationInfo;
if (!info || info.showType !== 0 || !Array.isArray(info.region) || info.region.length !== 4 ||
!info.region.every((part: number) => typeof part === 'number' && Number.isFinite(part))) {
return result;
}
const x = info.region[0];
const y = info.region[1];
const width = info.region[2];
const height = info.region[3];
const right = bounds.left + bounds.width;
const bottom = bounds.top + bounds.height;
if (width <= 0 || height <= 0 || x >= right || x + width <= bounds.left ||
y >= bottom || y + height <= bounds.top) {
return result;
}
if (width >= height && y + height >= bottom) {
result.bottom = bottom - Math.max(bounds.top, y);
} else if (width < height && x <= bounds.left) {
result.left = Math.min(right, x + width) - bounds.left;
} else if (width < height && x + width >= right) {
result.right = right - Math.max(bounds.left, x);
}
} catch (_) {
// 平板、旧系统或设置尚未就绪时,继续使用窗口标准避让区域。
}
return result;
}
export class WindowSafeArea {
private mainWindow: window.Window | undefined = undefined;
private context: common.UIAbilityContext | undefined = undefined;
private floatingNavigationValue: string = '';
private navigationRequest: number = 0;
private observingNavigation: boolean = false;
private readonly onFloatingNavigationChange = (): void => { this.refresh(); };
private readonly onAvoidAreaChange = (options: window.AvoidAreaOptions): void => {
if (options.type === window.AvoidAreaType.TYPE_SYSTEM ||
options.type === window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR) {
this.refresh();
}
};
private readonly onWindowSizeChange = (): void => {
this.refresh();
};
start(mainWindow: window.Window, context: common.UIAbilityContext): void {
this.stop();
this.mainWindow = mainWindow;
this.context = context;
mainWindow.on('avoidAreaChange', this.onAvoidAreaChange);
mainWindow.on('windowSizeChange', this.onWindowSizeChange);
try {
this.observingNavigation = settings.registerKeyObserver(context, FLOAT_NAVIGATION_KEY,
settings.domainName.USER_PROPERTY, this.onFloatingNavigationChange);
} catch (_) {}
this.refresh();
}
refresh(): void {
this.updateInsets();
const context = this.context;
if (!context) { return; }
const request = ++this.navigationRequest;
this.updateFloatingNavigation(context, request);
}
private async updateFloatingNavigation(context: common.UIAbilityContext, request: number): Promise<void> {
try {
const value = await settings.getValue(context, FLOAT_NAVIGATION_KEY, settings.domainName.USER_PROPERTY);
if (request !== this.navigationRequest || context !== this.context) { return; }
this.floatingNavigationValue = value;
this.updateInsets();
} catch (_) {
if (request !== this.navigationRequest || context !== this.context) { return; }
this.floatingNavigationValue = '';
this.updateInsets();
}
}
private updateInsets(): void {
const mainWindow = this.mainWindow;
if (!mainWindow) {
return;
}
try {
const uiContext = mainWindow.getUIContext();
const systemArea = mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
const insets = getNavigationInsets(mainWindow);
const floating = getFloatingNavigationInsets(this.floatingNavigationValue,
mainWindow.getWindowProperties().windowRect);
insets.left = Math.max(insets.left, floating.left);
insets.right = Math.max(insets.right, floating.right);
insets.bottom = Math.max(insets.bottom, floating.bottom);
AppStorage.setOrCreate<number>('statusBarHeight', uiContext.px2vp(systemArea.topRect.height));
AppStorage.setOrCreate<number>('navigationBarLeft', uiContext.px2vp(insets.left));
AppStorage.setOrCreate<number>('navigationBarRight', uiContext.px2vp(insets.right));
AppStorage.setOrCreate<number>('navigationBarBottom', uiContext.px2vp(insets.bottom));
// 三键导航是不可遮挡的系统区域;首页可单独收紧手势指示条上方的留白。
AppStorage.setOrCreate<number>('systemNavigationBarBottom',
uiContext.px2vp(Math.max(0, systemArea.bottomRect.height, floating.bottom)));
} catch (error) {
Logger.error('WindowSafeArea', '更新系统栏避让区域失败: ' + JSON.stringify(error));
}
}
stop(): void {
this.navigationRequest++;
if (this.context && this.observingNavigation) {
try {
settings.unregisterKeyObserver(this.context, FLOAT_NAVIGATION_KEY, settings.domainName.USER_PROPERTY);
} catch (_) {}
}
this.observingNavigation = false;
this.context = undefined;
this.floatingNavigationValue = '';
if (this.mainWindow) {
this.mainWindow.off('avoidAreaChange', this.onAvoidAreaChange);
this.mainWindow.off('windowSizeChange', this.onWindowSizeChange);
this.mainWindow = undefined;
}
}
}

View File

@ -1,32 +1,58 @@
/* rabbit-unimp-harmony-compat:v3 */
/* rabbit-unimp-harmony-compat:v6 */
// Legacy WGT startup reads these properties before mounting its first page.
// Only fill metadata absent from the Harmony SDK; do not emulate native Android APIs.
(function () {
if (typeof plus !== 'object' || !plus || typeof uni !== 'object' || !uni) return;
// WGT console forwarding stringifies its arguments. Vue component proxies can
// warn while being stringified, recursively re-entering that same logger.
if (typeof console === 'object' && console) {
['log', 'info', 'warn', 'error', 'debug'].forEach(function (level) {
var descriptor = Object.getOwnPropertyDescriptor(console, level);
// Both console and uni.__log__ are wrapped by the WGT's native log bridge.
// Reentry guards alone still let JSON.stringify walk a whole Vue component tree.
// Never enumerate objects (or invoke their getters/toJSON) at these log boundaries.
var logDepth = 0;
var guarded = new WeakSet();
function logValue(value) {
if (value === null) return value;
if (typeof value === 'object') {
try {
if (value instanceof Error) return String(value.stack || value.message).slice(0, 2048);
return Array.isArray(value) ? '[Array]' : '[Object]';
} catch (_) { return '[Object]'; }
}
if (typeof value === 'function') return '[Function]';
return typeof value === 'string' ? value.slice(0, 2048) : value;
}
function protectLog(target, key) {
var descriptor = Object.getOwnPropertyDescriptor(target, key);
if (descriptor && descriptor.configurable === false) return;
function guard(fn) {
if (typeof fn !== 'function') return fn;
if (typeof fn !== 'function' || guarded.has(fn)) return fn;
var active = false;
return function () {
if (active) return;
var wrapped = function () {
if (active || logDepth >= 8) return;
active = true;
try { return fn.apply(console, arguments); } finally { active = false; }
};
logDepth++;
try {
var args = [];
for (var i = 0; i < arguments.length && i < 16; i++) args.push(logValue(arguments[i]));
return fn.apply(target, args);
} finally {
logDepth--;
active = false;
}
var current = guard(console[level]);
Object.defineProperty(console, level, {
};
guarded.add(wrapped);
return wrapped;
}
var current = guard(target[key]);
Object.defineProperty(target, key, {
configurable: true, enumerable: true,
get: function () { return current; },
set: function (fn) { current = guard(fn); }
});
});
}
if (typeof console === 'object' && console) {
['log', 'info', 'warn', 'error', 'debug'].forEach(function (level) { protectLog(console, level); });
}
protectLog(uni, '__log__');
function systemInfo() {
try { return uni.getSystemInfoSync() || {}; } catch (_) { return {}; }
@ -50,6 +76,21 @@
var device = systemInfo();
plus.device = { vendor: device.brand || '', model: device.model || '' };
}
// Legacy templates read this field on every row but never define it on Harmony.
// Supply it before the first render instead of suppressing Vue's warning handler.
if (typeof Vue === 'object' && Vue) {
['createApp', 'createSSRApp', 'createVueApp'].forEach(function (key) {
var create = Vue[key];
var descriptor = Object.getOwnPropertyDescriptor(Vue, key);
if (typeof create !== 'function' || (descriptor && descriptor.writable === false)) return;
Vue[key] = function () {
var app = create.apply(this, arguments);
var properties = app && app.config && app.config.globalProperties;
if (properties && !('$system' in properties)) properties.$system = plus.os.name;
return app;
};
});
}
if (plus.runtime && !('version' in plus.runtime)) {
Object.defineProperty(plus.runtime, 'version', { configurable: true, enumerable: true, get: hostVersion });
}

View File

@ -6,7 +6,7 @@ export const BUILD_MODE_NAME = 'debug';
export const DEBUG = true;
export const TARGET_NAME = 'default';
export const CHANNEL = 'harmony';
export const BUILD_TIME = '2611021826';
export const BUILD_TIME = '2611031154';
/**
* BuildProfile Class is used only for compatibility purposes.

View File

@ -6,7 +6,7 @@ export const BUILD_MODE_NAME = 'debug';
export const DEBUG = true;
export const TARGET_NAME = 'default';
export const CHANNEL = 'harmony';
export const BUILD_TIME = '2611021826';
export const BUILD_TIME = '2611031154';
/**
* BuildProfile Class is used only for compatibility purposes.

View File

@ -1,4 +1,5 @@
import { isExistsUniMP, openUniMP, UniMP } from '@dcloudio/uni-app-runtime';
import { getNavigationInsets } from './WindowSafeArea';
import { AESDecrypt, PLATFORM, RELEASE_BASE_URL, Signature, TOKEN, TOKEN_LOGIN, USER_PROFILE } from '../constants/AppConstants';
import { ToastUtils } from '../dialog/ToastUtils';
import { UniVersionEntity, TradeData, UniIconEntity, UserProfile } from '../viewmodel/DataBean';
@ -238,7 +239,7 @@ async function uniMpConfig(context: UIContext): Promise<Record<string, string>>
const bundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
let safeBottom = 0;
try {
safeBottom = Math.max(0, Math.round(context.px2vp(AppUtil.getNavigationIndicatorHeight())));
safeBottom = Math.max(0, Math.ceil(context.px2vp(getNavigationInsets(AppUtil.getMainWindow()).bottom)));
} catch (_) {
// 无导航指示条或窗口尚未就绪时仍传有效值,避免旧 WGT 在 onLaunch 中读取 undefined。
}

View File

@ -34,7 +34,11 @@ export struct WebLayout {
// 页面加载完成后执行 JS
this.controller.runJavaScript('document.title = "HarmonyOS"');
})
.width('100%')
.height('100%')
}
.width('100%')
.layoutWeight(1)
}
.width('100%')
.height('100%')

View File

@ -26,7 +26,7 @@
{
"name": "default",
"output": {
"artifactName": "rabbit_harmony_v1.0.1_261121826"
"artifactName": "rabbit_harmony_v1.0.1_261131154"
}
},
{

View File

@ -3,7 +3,7 @@ import { KVStore } from '@ohos/common/src/main/ets/utils/KVStore';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
import { AppUtil } from '@pura/harmony-utils';
import { init } from '@dcloudio/uni-app-runtime';
import { initUniMpRuntime } from '@ohos/common/src/main/ets/utils/UniMpHostRuntime';
import { closeUniMpApps } from '@ohos/common/src/main/ets/utils/UniMpManager';
import * as wxopensdk from '@tencent/wechat_open_sdk';
import { emitter } from '@kit.BasicServicesKit';
@ -15,11 +15,13 @@ import { WXApi } from '@ohos/common/src/main/ets/viewmodel/CommonService';
import { setWechatAuthCode } from '@ohos/common/src/main/ets/utils/KVManager';
import { Logger } from '@ohos/common';
import { WX_BIND_AUTHOR } from '@ohos/common/src/main/ets/constants/AppConstants';
import { WindowSafeArea } from '@ohos/common/src/main/ets/utils/WindowSafeArea';
const DOMAIN = 0x0000;
export default class AppAbility extends UIAbility {
private readonly windowSafeArea: WindowSafeArea = new WindowSafeArea();
onCreate(want: Want, _launchParam: AbilityConstant.LaunchParam): void {
try {
@ -81,6 +83,7 @@ export default class AppAbility extends UIAbility {
onDestroy(): void {
this.windowSafeArea.stop();
closeUniMpApps();
// 生命周期管理:销毁
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy');
@ -90,34 +93,30 @@ export default class AppAbility extends UIAbility {
// 生命周期管理:主窗口已创建,为此功能设置主页
//获取主窗口,设置沉浸式
windowStage.getMainWindow((err, data) => {
if (err.code || !data) {
hilog.error(DOMAIN, 'AppAbility', 'Failed to get main window: %{public}s', JSON.stringify(err));
return;
}
let windowClass: window.Window = data;
this.windowSafeArea.start(windowClass, this.context);
// 1. 设置窗口为全屏模式(沉浸式)
windowClass.setWindowLayoutFullScreen(true);
windowClass.setWindowLayoutFullScreen(true).then(() => {
this.windowSafeArea.refresh();
}).catch((error: Error) => {
hilog.error(DOMAIN, 'AppAbility', 'Failed to set full screen layout: %{public}s', JSON.stringify(error));
});
// 2. 设置状态栏文字颜色(白色/黑色)
let sysBarProps: window.SystemBarProperties = {
statusBarContentColor: '#000000' // 黑色文字
};
windowClass.setSystemBarProperties(sysBarProps);
// 3. 获取避让区域(状态栏等)
// 注意:使用 window.AvoidAreaType.TYPE_SYSTEM 明确类型
let type: window.AvoidAreaType = window.AvoidAreaType.TYPE_SYSTEM;
let avoidArea: window.AvoidArea = windowClass.getWindowAvoidArea(type);
// 4. 计算高度并存储 (px2vp 是内置函数,直接使用)
let statusBarHeight: number = px2vp(avoidArea.topRect.height);
// 5. 存入全局存储,Key 名为 'statusBarHeight'
AppStorage.setOrCreate<number>('statusBarHeight', statusBarHeight);
});
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
//初始化UniMp
init(this, windowStage, {
debug: AppUtil.debug()
})
initUniMpRuntime(this, windowStage, AppUtil.debug());
// 加载页面(启动页)
windowStage.loadContent('pages/SplashScreenPage', (err) => {
@ -126,15 +125,18 @@ export default class AppAbility extends UIAbility {
return;
}
hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
this.windowSafeArea.refresh();
});
}
onWindowStageDestroy(): void {
this.windowSafeArea.stop();
// 生命周期管理:主窗口已销毁,释放与UI相关的资源
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
}
onForeground(): void {
this.windowSafeArea.refresh();
// 生命周期管理:已处于前台页面
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground');
}

View File

@ -1,4 +1,5 @@
import { NavigationPage } from './NavigationPage';
import { SafeAreaPage } from '../view/SafeAreaPage';
import { ToastUtils } from '@ohos/common/src/main/ets/dialog/ToastUtils';
@Builder
@ -18,6 +19,7 @@ struct Index {
//private context = this.getUIContext()?.getHostContext() as common.UIAbilityContext | undefined;
// private windowClass: window.Window | undefined = undefined;
private lastExitTime: number = 0;
@State private tabBarVisible: boolean = true;
/*
aboutToAppear() {
@ -55,7 +57,9 @@ struct Index {
build() {
Stack() {
NavigationPage();
SafeAreaPage({ compactGestureBottom: this.tabBarVisible }) {
NavigationPage((visible: boolean) => { this.tabBarVisible = visible; });
}
}
.width('100%')
.height('100%')

View File

@ -12,6 +12,7 @@ import { emitter } from '@kit.BasicServicesKit';
import { EVT_LOGIN_WX_AUTHOR_SUCCESS } from '@ohos/common/src/main/ets/constants/EventConstants';
import { Logger } from '@ohos/common';
import { LoginForHuawei } from '../view/LoginForHuawei';
import { SafeAreaPage } from '../view/SafeAreaPage';
/**
* 登录页面
@ -113,6 +114,17 @@ struct LoginPage {
}
build() {
Stack() {
SafeAreaPage() {
this.pageContent()
}
}
.width('100%')
.height('100%')
}
@Builder
pageContent() {
Navigation(this.pageStack) {
Stack() {
// 1. 背景层

View File

@ -9,9 +9,9 @@ import { TabBarItem } from '../viewmodel/LocalBean';
* 入口布局
*/
@Builder
export function NavigationPage() {
export function NavigationPage(onTabBarVisibilityChange: (visible: boolean) => void) {
Column() {
TabIndex()
TabIndex({ onTabBarVisibilityChange: onTabBarVisibilityChange })
}
}
@ -19,6 +19,7 @@ export function NavigationPage() {
export struct TabIndex {
@State currentIndex: number = 0;
@State private navBarVisible: boolean = true;
onTabBarVisibilityChange: (visible: boolean) => void = () => {};
private tabController: TabsController = new TabsController();
@State tabs: TabBarItem[] = TabsViewModel.getTabData();
@StorageLink('mainBreakpoint') currentBreakpoint: string = commonConstants.breakpointsInitializeName;
@ -130,7 +131,9 @@ export struct TabIndex {
}
.hideTitleBar(true)
.mode(NavigationMode.Stack)
.onNavBarStateChange((visible: boolean) => { this.navBarVisible = visible; })
.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
.onNavBarStateChange((visible: boolean) => {
this.navBarVisible = visible;
this.onTabBarVisibilityChange(visible);
})
}
}

View File

@ -17,6 +17,7 @@ import { CommonService } from '@ohos/common/src/main/ets/viewmodel/CommonService
import { UserProfile } from '@ohos/common/src/main/ets/viewmodel/DataBean';
import { registerUniProvider } from '@dcloudio/uni-app-runtime';
import { UniPaymentAlipayProviderImpl } from '@uni_modules/uni-payment-alipay';
import { SafeAreaPage } from '../view/SafeAreaPage';
/**
* 启动页 - Splash Screen
@ -31,6 +32,7 @@ struct SplashScreenPage {
@State canSkip: boolean = false;
@State hasAgreed?: boolean = undefined;
@State isShowCountDown: boolean = false;
@StorageProp('statusBarHeight') statusBarHeight: number = 0;
// 用于存储请求到的配置或错误状态
private isNavigated: boolean = false;
@ -178,6 +180,17 @@ struct SplashScreenPage {
}
build() {
Stack() {
SafeAreaPage() {
this.pageContent()
}
}
.width('100%')
.height('100%')
}
@Builder
pageContent() {
Stack() {
// 1. 背景图
Image($r('app.media.ic_splash_mask'))
@ -205,7 +218,7 @@ struct SplashScreenPage {
}
.position({ x: '100%', y: 0 }) // 定位到右上角
.markAnchor({ x: '100%', y: 0 }) // 锚点修正
.margin({ top: px2vp(AppStorage.get<number>('statusBarHeight') ?? 0) + 20, right: 20 }) // 避让状态栏
.margin({ top: this.statusBarHeight + 20, right: 20 }) // 已按窗口密度转换为 vp
.padding({ left: 12, right: 12, top: 6, bottom: 6 })
.backgroundColor('#40000000') // 40% 不透明度的黑色背景
.borderRadius(15) // 圆角胶囊形状

View File

@ -52,7 +52,7 @@ export struct HomeBanner {
Stack({ alignContent: Alignment.Bottom }) {
if (this.banners.length === 0) {
Image($r('app.media.ic_home_top_image')).width('100%').height('100%')
.objectFit(ImageFit.Fill)
.objectFit(ImageFit.Cover)
} else {
Swiper() {
ForEach(this.banners, (banner: HomeBannerEntity, index: number) => {
@ -100,29 +100,27 @@ export struct HomeBanner {
@Component
struct HomeBannerImage {
@Prop @Watch('resetImage') banner: HomeBannerEntity;
@State private imageRatio: number = BANNER_RATIO;
@State private imageLoaded: boolean = false;
private resetImage(): void {
this.imageRatio = BANNER_RATIO;
this.imageLoaded = false;
}
build() {
Stack({ alignContent: Alignment.Center }) {
Image($r('app.media.ic_home_top_image')).width('100%').height('100%').objectFit(ImageFit.Fill)
Image($r('app.media.ic_home_top_image')).width('100%').height('100%').objectFit(ImageFit.Cover)
.opacity(this.imageLoaded ? 0 : 1)
Image(this.banner.img ?? '')
.alt($r('app.media.ic_home_top_image'))
.width('100%').height((BANNER_RATIO / this.imageRatio * 100) + '%')
.objectFit(ImageFit.Fill)
// 等比铺满固定容器,超出部分居中裁剪,宽图也不会在上下露出背景。
.width('100%').height('100%')
.objectFit(ImageFit.Cover)
.onComplete((event) => {
if (event && event.width > 0 && event.height > 0) {
this.imageRatio = event.width / event.height;
this.imageLoaded = event.loadingStatus === 1;
}
})
.onError(() => { this.imageRatio = BANNER_RATIO; })
.onError(() => { this.imageLoaded = false; })
}.width('100%').height('100%').clip(true)
}
}

View File

@ -0,0 +1,33 @@
/**
* 所有路由入口共用的导航栏避让容器。
* Navigation 和它的 NavDestination 一起缩进,子页面无需重复添加底部间距。
* 顶部仍由页面自己的标题栏处理,保留首页背景的沉浸式效果。
*/
@Component
export struct SafeAreaPage {
@StorageProp('navigationBarLeft') private navigationBarLeft: number = 0;
@StorageProp('navigationBarRight') private navigationBarRight: number = 0;
@StorageProp('navigationBarBottom') private navigationBarBottom: number = 0;
@StorageProp('systemNavigationBarBottom') private systemNavigationBarBottom: number = 0;
// TabBar:手势区最多 12vp,三键导航完整避让后再留 8vp;详情页使用完整安全区。
@Prop compactGestureBottom: boolean = false;
@BuilderParam content: () => void;
build() {
Stack() {
this.content()
}
.width('100%')
.height('100%')
.backgroundColor(Color.White)
.padding({
left: this.navigationBarLeft,
right: this.navigationBarRight,
bottom: this.compactGestureBottom
? (this.systemNavigationBarBottom > 0
? Math.max(this.systemNavigationBarBottom, this.navigationBarBottom)
: Math.min(this.navigationBarBottom, 12))
: this.navigationBarBottom
})
}
}