[Ocho] artículos de aplicación Tauri - fondo transparente y esmerilado

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. TauriAunque v1.0la versión ha sido lanzada, hasta ahora, la información interna es deficiente, personalmente quiero Tauridesarrollar 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 wrycódigo fuente , podemos ver que el fondo de la aplicación Tauri se divide en tres capas:

  • La primera capa eswindow
  • La segunda capa eswebview
  • La tercera capa eshtml
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.jsonventana hay un transparentcampo , configurado para trueHabilitar Transparencia. (predeterminado false, no habilitado)

Nota: en macOS, debe tauri.conf.json > tauri > macOSPrivateApihabilitarse macos-private-api, el valor predeterminado es false, no habilitado. (Advertencia: App Store rechazará las aplicaciones que usan API privadas en macOS )

macOSPrivateApiCuando se establece trueen :

  • Habilitar API de fondo transparente
  • Establezca fullScreenEnabledla 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 是否设置了不透明背景色,将其修改为 RGBAtransparent。也可以通过 css 文件设置 body 样式。

<!DOCTYPE html>
<html>
  <body style="background-color: rgba(87,87,87,0.5);">
    <div id="root"></div>
  </body>
</html>

008-omb-uso

注意:在 macOS 中使用透明背景在页面跳转时会出现残影,暂未了解到相关解决方案

008-omb-imagen residual

磨砂背景

透明背景虽然很酷,但实用性低。因为在使用应用时很容易受到桌面背景的干扰,所以磨砂背景更符合使用场景。

官网并没有给出磨砂背景的相关配置,直接在第三层 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 中看到该依赖。

008-ventana-vibrancia

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.rsUso 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");
}

setupEs 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.

008-omb-window_vibrancy

Lectura relacionada


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

Supongo que te gusta

Origin juejin.im/post/7118935197215064078
Recomendado
Clasificación