A partir de este artículo, el artículo entrará en el enlace de combate real, que contendrá mucha exploración y aprendizaje personal. No hay garantía de que sea una buena práctica, pero intentaré documentar objetivamente el material relevante y el proceso de aprendizaje. Tauri
Aunque v1.0
la versión ha sido lanzada, hasta ahora, la información interna es deficiente, personalmente quiero Tauri
desarrollar un conjunto de herramientas (varias funciones pequeñas) basado en ella. Durante este proceso, me encontré con algunos problemas, o una serie de problemas, y quería registrarlos en forma de una serie de columnas (la buena memoria no es tan mala como la mala escritura), con la esperanza de ayudar a más nuevas tecnologías como yo. Apasionados . Si estos artículos le resultan útiles, puede iniciar este proyecto o reenviar los artículos a más personas que lo necesiten. Su apoyo también me dará mayor motivación para escribir, gracias.
Lectura de código fuente
Los documentos oficiales son materiales de aprendizaje de primera mano, cuando los documentos no satisfacen las necesidades, comprender su ecología o leer algunos códigos fuente puede tener beneficios inesperados.
Al leer el ejemplo del wry
código fuente , podemos ver que el fondo de la aplicación Tauri se divide en tres capas:
- La primera capa es
window
- La segunda capa es
webview
- La tercera capa es
html
fn main() -> wry::Result<()> {
use wry::{
application::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
},
webview::WebViewBuilder,
};
let event_loop = EventLoop::new();
let window = WindowBuilder::new()
.with_decorations(false)
// ✅ 第一层:
// There are actually three layer of background color when creating webview window.
// The first is window background...
.with_transparent(true)
.build(&event_loop)
.unwrap();
let _webview = WebViewBuilder::new(window)?
// ✅ 第二层:
// The second is on webview...
.with_transparent(true)
// ✅ 第三层:
// And the last is in html.
.with_url(
r#"data:text/html,
<!doctype html>
<html>
<body style="background-color:rgba(87,87,87,0.5);">hello</body>
<script>
window.onload = function() {
document.body.innerText = `hello, ${navigator.userAgent}`;
};
</script>
</html>"#,
)?
.build()?;
event_loop.run(move |event, _, control_flow| {
*control_flow = ControlFlow::Wait;
match event {
Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
} => *control_flow = ControlFlow::Exit,
_ => {}
}
});
}
Entonces, si queremos lograr aplicaciones esmeriladas o translúcidas, debemos comenzar con estas tres configuraciones.
Fondo transparente
configuración de tauri.conf.json
En la configuración de la tauri.conf.json
ventana hay un transparent
campo , configurado para true
Habilitar Transparencia. (predeterminado false
, no habilitado)
Nota: en macOS, debe tauri.conf.json > tauri > macOSPrivateApi
habilitarse macos-private-api
, el valor predeterminado es false
, no habilitado. (Advertencia: App Store rechazará las aplicaciones que usan API privadas en macOS )
macOSPrivateApi
Cuando se establece true
en :
- Habilitar API de fondo transparente
- Establezca
fullScreenEnabled
la preferencia entrue
{
"tauri": {
"macOSPrivateApi": true,
"windows": [
{
"width": 800,
"height": 600,
"resizable": true,
"fullscreen": false,
"title": "Oh My Box",
"transparent": true
}
]
}
}
configuración html
窗口配置中的 transparent
是开启第一层(window)和第二层(webview)的透明度。如果透明度未生效,请检查 html 是否设置了不透明背景色,将其修改为 RGBA
或 transparent
。也可以通过 css 文件设置 body 样式。
<!DOCTYPE html>
<html>
<body style="background-color: rgba(87,87,87,0.5);">
<div id="root"></div>
</body>
</html>
注意:在 macOS 中使用透明背景在页面跳转时会出现残影,暂未了解到相关解决方案
磨砂背景
透明背景虽然很酷,但实用性低。因为在使用应用时很容易受到桌面背景的干扰,所以磨砂背景更符合使用场景。
官网并没有给出磨砂背景的相关配置,直接在第三层 html 中使用 css 属性实现模糊效果也会存在一些问题,具体原因可以查看 Blurry and translucent background on a transparent window,issues 中作者提到可能会在 tauri v2
版本中支持此功能,过渡方案可以使用 tauri-apps/window-vibrancy 插件。所以接下来的配置将围绕 tauri-apps/window-vibrancy
进行:
Step 1
安装 window-vibrancy
依赖,推荐使用 cargo edit(该工具扩展了 Cargo,允许你通过从命令行修改 Cargo.toml 文件来添加、删除和升级依赖项) :
# 1. 命令进入 src-tauri 目录
cd src-tauri
# 2. 安装 window-vibrancy
cargo add window-vibrancy
安装完成后会在 Cargo.toml > dependencies
中看到该依赖。
Step 2
在 src-tauri/src
下新建 setup.rs
文件:
use tauri::{App, Manager};
use window_vibrancy::{self, NSVisualEffectMaterial};
/// setup
pub fn init(app: &mut App) -> std::result::Result<(), Box<dyn std::error::Error>> {
let win = app.get_window("main").unwrap();
// 仅在 macOS 下执行
#[cfg(target_os = "macos")]
window_vibrancy::apply_vibrancy(&win, NSVisualEffectMaterial::FullScreenUI)
.expect("Unsupported platform! 'apply_vibrancy' is only supported on macOS");
// 仅在 windows 下执行
#[cfg(target_os = "windows")]
window_vibrancy::apply_blur(&win, Some((18, 18, 18, 125)))
.expect("Unsupported platform! 'apply_blur' is only supported on Windows");
Ok(())
}
代码中的 #[cfg(target_os)]
是指条件编译,仅在目标的操作系统中执行相关代码,可以查看 conditional compilation - target_os 了解更多。
Paso 3
src-tauri/src/main.rs
Uso en setup.rs
:
mod setup;
fn main() {
let context = tauri::generate_context!();
tauri::Builder::default()
.setup(setup::init)
.run(context)
.expect("error while running OhMyBox application");
}
setup
Es un módulo de Rust, que simplemente divide el código según unidades lógicas o módulos funcionales. Consulte rust-by-example - mod para obtener más información.
Lectura relacionada
- NSVisualEffectView (desarrollador de Apple) : agrega translucidez y vitalidad a las vistas en la interfaz
Dirección del almacén: lencx/OhMyBox
se publicó por primera vez en GitHub Discussions
Siga la cuenta pública de "Floating Stillness", autor de cartas privadas, e ingrese al grupo de intercambio técnico de Tauri