suiss/ui
  • Docs
  • Components
  • Patterns
  • Interactions
  • Charts
  • Blocks
  • AI
GitHubCreate
DocsComponentsPatternsInteractionsChartsBlocksAICreate
Components84
  • Overview
  • Accordion
  • Alert
  • Alert Dialog
  • Alert Sheet
  • Amount Input
  • Aspect Ratio
  • Attachment
  • Avatar
  • Badge
  • Bottom Bar
  • Breadcrumb
  • Bubble
  • Button
  • Button Group
  • Calendar
  • Card
  • Carousel
  • Chart
  • Checkbox
  • Chip
  • Code Block
  • Collapsible
  • Combobox
  • Command
  • Context Menu
  • Dialog
  • Direction
  • Drawer
  • Dropdown Menu
  • Empty
  • FAB
  • Field
  • Fullscreen Menu
  • Haptics
  • Header
  • Hover Card
  • Icon
  • Input
  • Input Accessory Bar
  • Input Group
  • Input OTP
  • Item
  • Kbd
  • Keyboard Scroll View
  • Keypad
  • Label
  • Marker
  • Menubar
  • Message
  • Message Scroller
  • Native Select
  • Navigation Menu
  • Page Indicator
  • Pagination
  • Pin Pad
  • Popover
  • Progress
  • QR Scanner
  • Questionnaire
  • Radio Group
  • Resizable
  • Screen
  • Scroll Area
  • Select
  • Separator
  • Sheet
  • Sidebar
  • Signature Pad
  • Skeleton
  • Slider
  • Spinner
  • Switch
  • Tab Bar
  • Table
  • Tabs
  • Text
  • Textarea
  • Toast
  • Toggle
  • Toggle Group
  • Tooltip
  • Trace
  • Wheel Picker
  • Widget

suiss/ui · Component

Aspect Ratio

A container that keeps its content at a fixed width-to-height ratio.

Aspect Ratio is an open-source component from suiss/ui for React, React Native, SwiftUI and Jetpack Compose. The @esuiss/ui CLI copies its source into your project, so you own the code.

import { AspectRatio } from "@/components/ui/aspect-ratio"

export default function AspectRatioDemo() {
  return (
    <AspectRatio
      ratio={16 / 9}
      className="w-96 overflow-hidden rounded-2xl bg-muted"
    >
      <img
        src="https://images.unsplash.com/photo-1506744038136-46273834b3fb?w=800&q=80"
        alt="Mountain lake at sunrise"
        className="size-full object-cover"
      />
    </AspectRatio>
  )
}

AspectRatio is a single div that sets the CSS aspect-ratio property from the ratio prop. Its width follows the parent, and its height is derived from the ratio. It is positioned relative, so children can be absolutely positioned inside it.

Use it to reserve space for images, video or embeds so the layout does not shift while media loads.

Installation

$ pnpm dlx shadcn@latest add @esuiss/aspect-ratio

Works in any project with a components.json. See Installation for the one-line registry setup. Or use the suiss/ui CLI:

$ pnpm dlx @esuiss/ui@latest add aspect-ratio
  1. Add the cn helper.

  2. Copy and paste the following code into your project.

components/ui/aspect-ratio.tsx
import { cn } from "@/lib/utils"

function AspectRatio({
  ratio,
  className,
  ...props
}: React.ComponentProps<"div"> & { ratio: number }) {
  return (
    <div
      data-slot="aspect-ratio"
      style={
        {
          "--ratio": ratio,
        } as React.CSSProperties
      }
      className={cn("relative aspect-(--ratio)", className)}
  1. Update the import paths to match your project setup.

Usage

import { AspectRatio } from "@/components/ui/aspect-ratio"
<div className="w-96">
  <AspectRatio ratio={16 / 9} className="overflow-hidden rounded-2xl bg-muted">
    <img
      src="https://images.unsplash.com/photo-1506744038136-46273834b3fb?w=800&q=80"
      alt="Mountain lake at sunrise"
      className="size-full object-cover"
    />
  </AspectRatio>
</div>

Examples

Square

Set ratio={1} for a 1:1 frame.

import { AspectRatio } from "@/components/ui/aspect-ratio"

export default function AspectRatioSquare() {
  return (
    <AspectRatio
      ratio={1}
      className="w-96 overflow-hidden rounded-2xl bg-muted"
    >
      <img
        src="https://images.unsplash.com/photo-1506744038136-46273834b3fb?w=800&q=80"
        alt="Mountain lake at sunrise"
        className="size-full object-cover"
      />
    </AspectRatio>
  )
}

Portrait

Set ratio={3 / 4} for a frame that is taller than it is wide.

import { AspectRatio } from "@/components/ui/aspect-ratio"

export default function AspectRatioPortrait() {
  return (
    <AspectRatio
      ratio={3 / 4}
      className="w-96 overflow-hidden rounded-2xl bg-muted"
    >
      <img
        src="https://images.unsplash.com/photo-1506744038136-46273834b3fb?w=800&q=80"
        alt="Mountain lake at sunrise"
        className="size-full object-cover"
      />
    </AspectRatio>
  )
}

Placeholder

A 4:3 frame that holds centered placeholder text instead of an image.

import { AspectRatio } from "@/components/ui/aspect-ratio"

export default function AspectRatioPlaceholder() {
  return (
    <AspectRatio
      ratio={4 / 3}
      className="w-96 overflow-hidden rounded-2xl bg-muted"
    >
      <div className="text-muted-foreground flex size-full items-center justify-center text-sm">
        4:3
      </div>
    </AspectRatio>
  )
}

API Reference

AspectRatio

The ratio-locked container.

PropTypeDefault
rationumberRequired

Also accepts the props of React.ComponentProps<"div">.

Pass ratio as width divided by height, typically written as a division such as 16 / 9, 4 / 3 or 1. The ratio is passed through the --ratio CSS custom property and applied with the aspect-(--ratio) class. Give media inside it className="size-full object-cover" to fill the frame, and add overflow-hidden and a radius class to clip the content to rounded corners. Style it through data-slot="aspect-ratio".

Web

Web preview

import { Image } from "react-native"
import { AspectRatio } from "@/components/ui/aspect-ratio"

export default function AspectRatioDemo() {
  return (
    <AspectRatio ratio={16 / 9} className="w-full overflow-hidden rounded-lg">
      <Image
        source={{
          uri: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=800&dpr=2&q=80",
        }}
        className="h-full w-full"
      />
    </AspectRatio>
  )
}
import { Image } from "react-native"
import { AspectRatio } from "@/components/ui/aspect-ratio"
import { radius } from "@/components/ui/theme"

export default function AspectRatioDemo() {
  return (
    <AspectRatio ratio={16 / 9} style={{ width: "100%", overflow: "hidden", borderRadius: radius.lg }}>
      <Image
        source={{
          uri: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=800&dpr=2&q=80",
        }}
        style={{ height: "100%", width: "100%" }}
      />
    </AspectRatio>
  )
}
import SwiftUI

struct AspectRatioExample: View {
  var body: some View {
    AspectRatio(ratio: 16 / 9) {
      AspectRatioPhoto()
    }
    .clipShape(RoundedRectangle(cornerRadius: Radius.lg, style: .continuous))
    .frame(maxWidth: .infinity)
  }
}

struct AspectRatioPhoto: View {
  var body: some View {
    AsyncImage(
      url: URL(string: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=800&dpr=2&q=80")
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.painter.BrushPainter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.Dp
import com.adamglin.phosphoricons.regular.Image
import com.esuiss.ui.components.AspectRatio

AspectRatio is a View that sets the aspectRatio style from its ratio prop. Its height follows from the width it is given, so the content keeps its shape at any screen size.

Use it for images, video thumbnails and placeholders that must not stretch.

Installation

$ pnpm dlx shadcn@latest add @esuiss/aspect-ratio

See Installation for the components.json setup. Or use the suiss/ui CLI:

$ pnpm dlx @esuiss/ui@latest add aspect-ratio
$ pnpm dlx shadcn@latest add @esuiss/aspect-ratio

See Installation for the components.json setup. Or use the suiss/ui CLI:

$ pnpm dlx @esuiss/ui@latest add aspect-ratio --platform swift
$ pnpm dlx shadcn@latest add @esuiss/aspect-ratio

See Installation for the components.json setup. Or use the suiss/ui CLI:

$ pnpm dlx @esuiss/ui@latest add aspect-ratio --platform kotlin
  1. Copy the primitives it uses into components/primitives:
uniwind/components/primitives/aspect-ratio.tsx
import * as React from "react"
import { View } from "react-native"
import type { BaseUIComponentProps } from "./types"
import { useRender } from "./use-render"

interface RootState {
  ratio: number
}

type RootProps = BaseUIComponentProps<typeof View, RootState> & {
  ratio?: number | undefined
}

function Root({
  ratio = 1,
  render,
uniwind/components/primitives/hooks.ts
import * as React from "react"
import { BackHandler } from "react-native"

function useEffectEvent<TArgs extends readonly unknown[], TResult>(
  callback: (...args: TArgs) => TResult
): (...args: TArgs) => TResult {
  const callbackRef = React.useRef(callback)

  React.useLayoutEffect(() => {
    callbackRef.current = callback
  })

  return React.useCallback(
    (...args: TArgs): TResult => callbackRef.current(...args),
    []
  )
uniwind/components/primitives/merge-props.ts
type AnyProps = Record<string, unknown>

type PropsGetter = (previous: AnyProps) => object

type MergePropsInput = object | PropsGetter | null | undefined

type Handler = (...args: unknown[]) => unknown

type StyleCallback = (state: never) => unknown

const EMPTY_PROPS: AnyProps = {}

function isEventHandler(key: string, value: unknown) {
  const code0 = key.charCodeAt(0)
  const code1 = key.charCodeAt(1)
  const code2 = key.charCodeAt(2)
uniwind/components/primitives/types.ts
import type * as React from "react"
import type {
  GestureResponderEvent,
  HostInstance,
  NativeSyntheticEvent,
  StyleProp,
  ViewStyle,
} from "react-native"

type Side = "top" | "bottom" | "left" | "right"
type Align = "start" | "center" | "end"
type Orientation = "horizontal" | "vertical"

type ComponentRenderFn<Props, State> = (
  props: Props,
  state: State
uniwind/components/primitives/use-render.tsx
import * as React from "react"
import { useComposedRefs } from "./hooks"
import { mergeClassNames, mergeProps, mergeStyles } from "./merge-props"
import type { ClassNameProp, RenderProp, StyleValue } from "./types"

type AnyProps = Record<string, unknown>

type RefInput<T> = React.Ref<T> | undefined

interface UseRenderParameters<State, RefType = unknown, Props = AnyProps> {
  defaultComponent?: React.ElementType | undefined
  render?: RenderProp<Props, State> | undefined
  props?: object | readonly (object | null | undefined)[] | undefined
  state?: State | undefined
  ref?: RefInput<RefType> | readonly RefInput<RefType>[] | undefined
  className?: ClassNameProp<State>
  1. Copy and paste the following code into components/ui/aspect-ratio.tsx:
uniwind/components/ui/aspect-ratio.tsx
import * as AspectRatioPrimitive from "@/components/primitives/aspect-ratio"

const AspectRatio = AspectRatioPrimitive.Root

export { AspectRatio }
  1. Update the import paths to match your project setup.
  1. Copy the primitives it uses into components/primitives:
nativewind/components/primitives/aspect-ratio.tsx
import * as React from "react"
import { View } from "react-native"
import type { BaseUIComponentProps } from "./types"
import { useRender } from "./use-render"

interface RootState {
  ratio: number
}

type RootProps = BaseUIComponentProps<typeof View, RootState> & {
  ratio?: number | undefined
}

function Root({
  ratio = 1,
  render,
nativewind/components/primitives/hooks.ts
import * as React from "react"
import { BackHandler } from "react-native"

function useEffectEvent<TArgs extends readonly unknown[], TResult>(
  callback: (...args: TArgs) => TResult
): (...args: TArgs) => TResult {
  const callbackRef = React.useRef(callback)

  React.useLayoutEffect(() => {
    callbackRef.current = callback
  })

  return React.useCallback(
    (...args: TArgs): TResult => callbackRef.current(...args),
    []
  )
nativewind/components/primitives/merge-props.ts
type AnyProps = Record<string, unknown>

type PropsGetter = (previous: AnyProps) => object

type MergePropsInput = object | PropsGetter | null | undefined

type Handler = (...args: unknown[]) => unknown

type StyleCallback = (state: never) => unknown

const EMPTY_PROPS: AnyProps = {}

function isEventHandler(key: string, value: unknown) {
  const code0 = key.charCodeAt(0)
  const code1 = key.charCodeAt(1)
  const code2 = key.charCodeAt(2)
nativewind/components/primitives/types.ts
import type * as React from "react"
import type {
  GestureResponderEvent,
  HostInstance,
  NativeSyntheticEvent,
  StyleProp,
  ViewStyle,
} from "react-native"

type Side = "top" | "bottom" | "left" | "right"
type Align = "start" | "center" | "end"
type Orientation = "horizontal" | "vertical"

type ComponentRenderFn<Props, State> = (
  props: Props,
  state: State
nativewind/components/primitives/use-render.tsx
import * as React from "react"
import { useComposedRefs } from "./hooks"
import { mergeClassNames, mergeProps, mergeStyles } from "./merge-props"
import type { ClassNameProp, RenderProp, StyleValue } from "./types"

type AnyProps = Record<string, unknown>

type RefInput<T> = React.Ref<T> | undefined

interface UseRenderParameters<State, RefType = unknown, Props = AnyProps> {
  defaultComponent?: React.ElementType | undefined
  render?: RenderProp<Props, State> | undefined
  props?: object | readonly (object | null | undefined)[] | undefined
  state?: State | undefined
  ref?: RefInput<RefType> | readonly RefInput<RefType>[] | undefined
  className?: ClassNameProp<State>
  1. Copy and paste the following code into components/ui/aspect-ratio.tsx:
nativewind/components/ui/aspect-ratio.tsx
import * as AspectRatioPrimitive from "@/components/primitives/aspect-ratio"

const AspectRatio = AspectRatioPrimitive.Root

export { AspectRatio }
  1. Update the import paths to match your project setup.
  1. Copy the primitives it uses into components/primitives:
stylesheet/components/primitives/aspect-ratio.tsx
import * as React from "react"
import { View } from "react-native"
import type { BaseUIComponentProps } from "./types"
import { useRender } from "./use-render"

interface RootState {
  ratio: number
}

type RootProps = BaseUIComponentProps<typeof View, RootState> & {
  ratio?: number | undefined
}

function Root({
  ratio = 1,
  render,
stylesheet/components/primitives/hooks.ts
import * as React from "react"
import { BackHandler } from "react-native"

function useEffectEvent<TArgs extends readonly unknown[], TResult>(
  callback: (...args: TArgs) => TResult
): (...args: TArgs) => TResult {
  const callbackRef = React.useRef(callback)

  React.useLayoutEffect(() => {
    callbackRef.current = callback
  })

  return React.useCallback(
    (...args: TArgs): TResult => callbackRef.current(...args),
    []
  )
stylesheet/components/primitives/merge-props.ts
type AnyProps = Record<string, unknown>

type PropsGetter = (previous: AnyProps) => object

type MergePropsInput = object | PropsGetter | null | undefined

type Handler = (...args: unknown[]) => unknown

type StyleCallback = (state: never) => unknown

const EMPTY_PROPS: AnyProps = {}

function isEventHandler(key: string, value: unknown) {
  const code0 = key.charCodeAt(0)
  const code1 = key.charCodeAt(1)
  const code2 = key.charCodeAt(2)
stylesheet/components/primitives/types.ts
import type * as React from "react"
import type {
  GestureResponderEvent,
  HostInstance,
  NativeSyntheticEvent,
  StyleProp,
  ViewStyle,
} from "react-native"

type Side = "top" | "bottom" | "left" | "right"
type Align = "start" | "center" | "end"
type Orientation = "horizontal" | "vertical"

type ComponentRenderFn<Props, State> = (
  props: Props,
  state: State
stylesheet/components/primitives/use-render.tsx
import * as React from "react"
import { useComposedRefs } from "./hooks"
import { mergeClassNames, mergeProps, mergeStyles } from "./merge-props"
import type { ClassNameProp, RenderProp, StyleValue } from "./types"

type AnyProps = Record<string, unknown>

type RefInput<T> = React.Ref<T> | undefined

interface UseRenderParameters<State, RefType = unknown, Props = AnyProps> {
  defaultComponent?: React.ElementType | undefined
  render?: RenderProp<Props, State> | undefined
  props?: object | readonly (object | null | undefined)[] | undefined
  state?: State | undefined
  ref?: RefInput<RefType> | readonly RefInput<RefType>[] | undefined
  className?: ClassNameProp<State>
  1. Copy and paste the following code into components/ui/aspect-ratio.tsx:
stylesheet/components/ui/aspect-ratio.tsx
import * as AspectRatioPrimitive from "@/components/primitives/aspect-ratio"

const AspectRatio = AspectRatioPrimitive.Root

export { AspectRatio }
  1. Update the import paths to match your project setup.
  1. Target iOS 17 or later.

  2. Add the Swift package to your app:

Package.swift
.package(url: "https://github.com/phosphor-icons/swift", from: "2.1.0")
  1. Copy the theme files every view uses:
swift/Theme/Theme.swift
import CoreText
import SwiftUI
import UIKit

struct RGBA: Sendable {
  let red: CGFloat
  let green: CGFloat
  let blue: CGFloat
  let alpha: CGFloat

  init(_ hex: UInt32, _ alpha: CGFloat = 1) {
    red = CGFloat((hex >> 16) & 0xFF) / 255
    green = CGFloat((hex >> 8) & 0xFF) / 255
    blue = CGFloat(hex & 0xFF) / 255
    self.alpha = alpha
  }
swift/Theme/Tokens.swift
import SwiftUI

public enum EsuissColor {
  public static let background = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0x000000))
  public static let foreground = Color.adaptive(light: .init(0x1D1D1F), dark: .init(0xF5F5F7))
  public static let card = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0x1D1D1F))
  public static let cardForeground = Color.adaptive(light: .init(0x1D1D1F), dark: .init(0xF5F5F7))
  public static let popover = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0x1D1D1F))
  public static let popoverForeground = Color.adaptive(light: .init(0x1D1D1F), dark: .init(0xF5F5F7))
  public static let primary = Color.adaptive(light: .init(0x0071E3), dark: .init(0x0A84FF))
  public static let primaryForeground = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0xFFFFFF))
  public static let secondary = Color.adaptive(light: .init(0x000000, 0.04), dark: .init(0xFFFFFF, 0.1))
  public static let secondaryForeground = Color.adaptive(light: .init(0x1D1D1F), dark: .init(0xF5F5F7))
  public static let muted = Color.adaptive(light: .init(0xF5F5F7), dark: .init(0x161617))
  public static let mutedForeground = Color.adaptive(light: .init(0x6E6E73), dark: .init(0x86868B))
  public static let accent = Color.adaptive(light: .init(0x000000, 0.06), dark: .init(0xFFFFFF, 0.1))
  1. Copy the source:
swift/Components/AspectRatio.swift
import SwiftUI

public struct AspectRatio<Content: View>: View {
  let ratio: CGFloat
  let content: Content

  public init(ratio: CGFloat = 1, @ViewBuilder content: () -> Content) {
    self.ratio = ratio
    self.content = content()
  }

  public var body: some View {
    Color.clear
      .aspectRatio(ratio, contentMode: .fit)
      .overlay {
        content
  1. Add the files to your app target.
  1. Apply the Compose compiler plugin, enable Compose, set compileSdk to 37 or higher and minSdk to 24 or higher, and add the dependencies:
build.gradle.kts
plugins {
    id("org.jetbrains.kotlin.plugin.compose")
}

android {
    compileSdk = 37
    defaultConfig { minSdk = 24 }
    buildFeatures { compose = true }
}

dependencies {
    implementation(platform("androidx.compose:compose-bom:2026.09.00"))
    implementation("androidx.compose.foundation:foundation")
    implementation("androidx.compose.ui:ui")
    implementation("com.adamglin:phosphor-icon-android:1.0.0")
}
  1. Copy the theme files every view uses:
kotlin/theme/Theme.kt
package com.esuiss.ui.theme

import android.content.res.AssetManager
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.dropShadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.shadow.Shadow as DropShadow
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
kotlin/theme/Tokens.kt
package com.esuiss.ui.theme

import androidx.compose.runtime.Immutable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp

@Immutable
data class Colors(
    val background: Color,
    val foreground: Color,
    val card: Color,
    val cardForeground: Color,
    val popover: Color,
    val popoverForeground: Color,
    val primary: Color,
  1. Copy the source:
kotlin/components/AspectRatio.kt
package com.esuiss.ui.components

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier

@Composable
fun AspectRatio(
    ratio: Float,
    modifier: Modifier = Modifier,
    content: @Composable BoxScope.() -> Unit,
) {
    Box(
  1. Update the com.esuiss.ui package names to match your project.

Usage

import { View, Image } from "react-native"
import { AspectRatio } from "@/components/ui/aspect-ratio"

<View className="w-full overflow-hidden rounded-lg">
  <AspectRatio ratio={16 / 9}>
    <Image source={{ uri: imageUri }} className="h-full w-full" />
  </AspectRatio>
</View>
import { View, Image } from "react-native"
import { AspectRatio } from "@/components/ui/aspect-ratio"
import { radius } from "@/components/ui/theme"

<View style={{ width: "100%", overflow: "hidden", borderRadius: radius.lg }}>
  <AspectRatio ratio={16 / 9}>
    <Image source={{ uri: imageUri }} style={{ height: "100%", width: "100%" }} />
  </AspectRatio>
</View>
import SwiftUI

struct AspectRatioExample: View {
  var body: some View {
    AspectRatio(ratio: 16 / 9) {
      AspectRatioPhoto()
    }
    .clipShape(RoundedRectangle(cornerRadius: Radius.lg, style: .continuous))
    .frame(maxWidth: .infinity)
  }
}

struct AspectRatioPhoto: View {
  var body: some View {
    AsyncImage(
      url: URL(string: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=800&dpr=2&q=80")
    ) { phase in
      if let image = phase.image {
        image.resizable().scaledToFill()
      } else {
        EsuissColor.muted
      }
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
  }
}
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.painter.BrushPainter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.Dp
import com.adamglin.phosphoricons.regular.Image
import com.esuiss.ui.components.AspectRatio
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Palette
import com.esuiss.ui.theme.Radius

@Composable
fun AspectRatioExample() {
    AspectRatioPhoto(null, 16f / 9f)
}

@Composable
fun AspectRatioPhoto(width: Dp?, ratio: Float) {
    val colors = EsuissTheme.colors
    val photo = remember(colors) { BrushPainter(Brush.linearGradient(listOf(Palette.teal500, Palette.blue500, Palette.indigo500))) }
    Box(
        (if (width != null) Modifier.width(width) else Modifier.fillMaxWidth())
            .clip(RoundedCornerShape(Radius.lg)),
    ) {
        AspectRatio(ratio) {
            Image(photo, contentDescription = null, modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop)
        }
    }
}

Examples

Square

Set ratio={1} for a square image.

Web

Web preview

import { Image } from "react-native"
import { AspectRatio } from "@/components/ui/aspect-ratio"

export default function AspectRatioSquare() {
  return (
    <AspectRatio ratio={1} className="w-48 overflow-hidden rounded-lg">
      <Image
        source={{
          uri: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=800&dpr=2&q=80",
        }}
        className="h-full w-full"
      />
    </AspectRatio>
  )
}
import { Image } from "react-native"
import { AspectRatio } from "@/components/ui/aspect-ratio"
import { radius } from "@/components/ui/theme"

export default function AspectRatioSquare() {
  return (
    <AspectRatio ratio={1} style={{ width: 192, overflow: "hidden", borderRadius: radius.lg }}>
      <Image
        source={{
          uri: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=800&dpr=2&q=80",
        }}
        style={{ height: "100%", width: "100%" }}
      />
    </AspectRatio>
  )
}
import SwiftUI

struct AspectRatioSquareExample: View {
  var body: some View {
    AspectRatio(ratio: 1) {
      AspectRatioPhoto()
    }
    .clipShape(RoundedRectangle(cornerRadius: Radius.lg, style: .continuous))
    .frame(width: 192)
  }
}

struct AspectRatioPhoto: View {
  var body: some View {
    AsyncImage(
      url: URL(string: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=800&dpr=2&q=80")
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.painter.BrushPainter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.adamglin.phosphoricons.regular.Image

Portrait

Set ratio={9 / 16} for a tall image.

Web

Web preview

import { Image } from "react-native"
import { AspectRatio } from "@/components/ui/aspect-ratio"

export default function AspectRatioPortrait() {
  return (
    <AspectRatio ratio={9 / 16} className="w-40 overflow-hidden rounded-lg">
      <Image
        source={{
          uri: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=800&dpr=2&q=80",
        }}
        className="h-full w-full"
      />
    </AspectRatio>
  )
}
import { Image } from "react-native"
import { AspectRatio } from "@/components/ui/aspect-ratio"
import { radius } from "@/components/ui/theme"

export default function AspectRatioPortrait() {
  return (
    <AspectRatio ratio={9 / 16} style={{ width: 160, overflow: "hidden", borderRadius: radius.lg }}>
      <Image
        source={{
          uri: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=800&dpr=2&q=80",
        }}
        style={{ height: "100%", width: "100%" }}
      />
    </AspectRatio>
  )
}
import SwiftUI

struct AspectRatioPortraitExample: View {
  var body: some View {
    AspectRatio(ratio: 9 / 16) {
      AspectRatioPhoto()
    }
    .clipShape(RoundedRectangle(cornerRadius: Radius.lg, style: .continuous))
    .frame(width: 160)
  }
}

struct AspectRatioPhoto: View {
  var body: some View {
    AsyncImage(
      url: URL(string: "https://images.unsplash.com/photo-1588345921523-c2dcdb7f1dcd?w=800&dpr=2&q=80")
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.painter.BrushPainter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.adamglin.phosphoricons.regular.Image

Placeholder

A placeholder surface with an icon instead of an image.

Web

Web preview

import { ImageIcon } from "phosphor-react-native"
import { View } from "react-native"
import { AspectRatio } from "@/components/ui/aspect-ratio"
import { Icon } from "@/components/ui/icon"
import { Text } from "@/components/ui/text"

export default function AspectRatioPlaceholder() {
  return (
    <AspectRatio ratio={16 / 9} className="w-full">
      <View className="bg-muted h-full w-full items-center justify-center gap-2 rounded-lg">
        <Icon as={ImageIcon} className="text-muted-foreground size-8" />
        <Text variant="muted">16 / 9</Text>
      </View>
    </AspectRatio>
  )
}
import { ImageIcon } from "phosphor-react-native"
import { View } from "react-native"
import { AspectRatio } from "@/components/ui/aspect-ratio"
import { Icon } from "@/components/ui/icon"
import { Text } from "@/components/ui/text"
import { radius, useTheme } from "@/components/ui/theme"

export default function AspectRatioPlaceholder() {
  const { colors } = useTheme()
  return (
    <AspectRatio ratio={16 / 9} style={{ width: "100%" }}>
      <View style={{ backgroundColor: colors.muted, height: "100%", width: "100%", alignItems: "center", justifyContent: "center", gap: 8, borderRadius: radius.lg }}>
        <Icon as={ImageIcon} color={colors.mutedForeground} size={32} />
        <Text variant="muted">16 / 9</Text>
      </View>
    </AspectRatio>
import PhosphorSwift
import SwiftUI

struct AspectRatioPlaceholderExample: View {
  var body: some View {
    AspectRatio(ratio: 16 / 9) {
      VStack(spacing: 8) {
        Ph.image.regular
          .frame(width: 32, height: 32)
          .foregroundStyle(EsuissColor.mutedForeground)
        Text("16 / 9")
          .textVariant(.muted)
      }
      .frame(maxWidth: .infinity, maxHeight: .infinity)
      .background(EsuissColor.muted, in: RoundedRectangle(cornerRadius: Radius.lg, style: .continuous))
    }
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Regular
import com.adamglin.phosphoricons.regular.Image
import com.esuiss.ui.components.AspectRatio
import com.esuiss.ui.components.Icon
import com.esuiss.ui.components.Text

Accessibility

  • The view adds no role; give images their own accessibilityLabel.

API Reference

AspectRatio

A view that keeps its width and height at a fixed ratio.

PropTypeDefault
rationumber1
renderReact.ReactElement | ((props, state) => React.ReactElement)-

Also accepts the props of View.

Pass ratio as width divided by height, such as 16 / 9. Size the content inside with h-full w-full, and put rounding or clipping on a parent view. Use render to render another element in place of the default View.

AspectRatio

A view that keeps its width and height at a fixed ratio.

ParameterTypeDefault
ratioCGFloat1
content() -> Content-

AspectRatio

A view that keeps its width and height at a fixed ratio.

ParameterTypeDefault
ratioFloat-
modifierModifierModifier
content@Composable BoxScope.() -> Unit-
NextAttachmentPreviousAmount Input

On this page

  1. 01Installation
  2. 02Usage
  3. 03Examples
    • Square
    • Portrait
    • Placeholder
  4. 04API Reference
    • AspectRatio
  5. 05Installation
  6. 06Usage
  7. 07Examples
    • Square
    • Portrait
    • Placeholder
  8. 08Accessibility
  9. 09API Reference
    • AspectRatio
    • AspectRatio
    • AspectRatio