# Rive
> This file is very large and may be truncated. For an index of this content, please refer to https://rive.app/docs/llms.txt instead.
# Account Management
Source: https://rive.app/docs/account-admin/account-overview/account-management
Your account settings live at [rive.app/account](https://rive.app/account?utm_source=docs\&utm_medium=content).
You can also get there by clicking your name (top-left corner) → Manage Account.
From here you can:
* Update your email, password, or profile
* Manage your workspaces and billing
* View notifications
* Manage embed URLs for your files
Your workspaces are listed in the left sidebar. Click "Manage Workspace" next to any workspace to change its plan, update payment, or invite members.
**Questions?** [Contact support](https://forms.rive.app/support?utm_medium=support_page).
# Billing Changes
Source: https://rive.app/docs/account-admin/account-overview/billing-changes
How to update your card, change your plan, or manage billing for your Rive workspace.
⚠️ If you have a pending change (like a scheduled cancellation), you can't make other billing changes until it's resolved. [Contact support](https://forms.rive.app/support?utm_medium=support_page) if you're stuck.
## Where to manage billing
1. Go to [rive.app/account](https://rive.app/account?utm_source=docs\&utm_medium=content)
2. Find your workspace under "Workspaces"
3. Click "Manage Workspace"
From here you can:
* **Change Plan** → Switch between Free and Voyager
* **Manage Billing** → Opens Stripe to update your payment card
⚠️ "Create a Workspace" creates a NEW workspace. It does not update your current plan.
***
## Update your payment card
1. Click "Manage Billing" to open the Stripe Customer Portal
2. Go to "Payment Methods"
3. Add your new card
4. Click "Set as default"
5. Remove the old card (optional)
If your workspace was downgraded due to a failed payment, updating your card alone will not restore access. After updating your payment method, click "Upgrade Plan" and select a paid plan again.
Access is typically restored within a few minutes.
***
## Change your plan
Click "Change Plan" from the Manage Workspace page to switch between Free and Voyager.
**Have legacy/grandfathered pricing?** [Contact support](https://forms.rive.app/support?utm_medium=support_page) and we'll process the change for you. This includes switching between monthly and annual billing.
***
## If your card keeps getting declined
Call your bank first. Common issues:
* International transactions blocked (Rive uses Stripe)
* Bank flagged the charge as suspicious
After your bank clears it, wait 30 minutes and try again. Still not working? Try a different card or [contact support](https://forms.rive.app/support?utm_medium=support_page).
***
## Multiple workspaces?
Each workspace has its own billing. Make sure you're managing the right one—check the workspace name at the top of the Manage Workspace page.
***
## For workspace members
Only the workspace owner can update billing. If you're seeing access errors due to a payment issue, let the owner know.
**Questions?** [Contact support](https://forms.rive.app/support?utm_medium=support_page).
# Cancelling My Plan
Source: https://rive.app/docs/account-admin/account-overview/cancel-my-account
Cancel a workspace's paid plan.
Plans are managed per workspace. Cancelling a plan only affects the selected workspace and does not affect any other workspaces you belong to.
**Step 1**
Go to [rive.app/account](https://rive.app/account?utm_source=docs\&utm_medium=content).
**Step 2**
Click **Manage Workspace** for the workspace whose plan you want to cancel.
**Step 3**
Click **Cancel Plan**, which will redirect you to Stripe.
> [!NOTE]
>
> If you don't see the Cancel Plan button, the workspace may already be on the Free plan.
>
> If not, please [contact support](https://forms.rive.app/support?utm_medium=support_page).
**Step 4**
Click **Cancel Plan** to confirm.
You'll keep access until the end of your current billing period. After that, the workspace will move to a Free plan.
> [!NOTE]
>
> Once cancellation is scheduled, you won't be able to make changes to the workspace's plan until the cancellation takes effect at the end of the current billing period.
## FAQs
> [accordion] Can I undo a cancellation?
>
> If you change your mind or need to make changes, [contact support](https://forms.rive.app/support?utm_medium=support_page) to remove the pending cancellation first.
> [accordion] How do I permanently delete my workspace and all my files?
>
> See [Deleting a Workspace](/docs/home/account-admin/workspaces/delete-a-workspace).
**Questions?** [Contact support](https://forms.rive.app/support?utm_medium=support_page).
# Creating an Account
Source: https://rive.app/docs/account-admin/account-overview/creating-an-account
To create a Rive account, go to [rive.app/signup](https://rive.app/signup/?redirect=%2Faccount%2Fteams%2F\&utm_source=docs\&utm_medium=content) and follow the signup steps.
After signing up, you can use Rive for free or upgrade a workspace later.
## FAQs
> [accordion] Can I create a free account?
>
> Yes. You can create a free Rive account and start using the editor without upgrading.
> [accordion] Can I create a new account with an email address I used before?
>
> If you previously deleted a Rive account with the same email address, you won't be able to create a new account with that email. [Contact support](https://forms.rive.app/support?utm_medium=support_page) to restore the old account instead.
> [accordion] How do I collaborate with other people?
>
> To collaborate with others, create or join a workspace. See [Creating a Workspace](/docs/account-admin/workspaces/managing-workspaces#creating-a-new-workspace).
> [accordion] Do you offer student discounts?
>
> Yes. See [Rive Student Plan Request](https://forms.rive.app/education?utm_medium=support_page) for details.
# Delete My Account
Source: https://rive.app/docs/account-admin/account-overview/delete-my-account
Deleting your account is permanent and removes all your data after 90 days.
## Before you can delete
You need to remove all workspaces from your account first:
1. Go to [rive.app/account](https://rive.app/account?utm_source=docs\&utm_medium=content)
2. For each workspace you own:
* Click "Manage Workspace"
* If it's a paid plan, click "Cancel Plan" first
* Then click "Delete Workspace"
3. Once all workspaces are removed, you can delete your account
## What happens to your data
* Your account and data are deleted 90 days after cancellation
* Files you contributed to other people's workspaces are **not** deleted
* Content others have remixed from your Marketplace uploads is **not** deleted
## If you own a workspace with members
Deleting your account suspends access for everyone in your workspace. If you want the workspace to continue, transfer ownership to another admin before deleting your account. See [Transfer Workspace Ownership](/docs/account-admin/workspaces/managing-workspaces#transferring-workspace-ownership).
If you delete your account and later want to use the same email address, you won't be able to create a new account. [Contact support](https://forms.rive.app/support?utm_medium=support_page) to restore your account instead. Note: we cannot guarantee your files will still be available.
# Downloading My Receipt/Invoice
Source: https://rive.app/docs/account-admin/account-overview/downloading-my-receipt-or-invoice
Invoice links in email expire after about a week. If your link no longer works, you can always download invoices directly from your account.
1. Go to [rive.app/account](https://rive.app/account?utm_source=docs\&utm_medium=content)
2. Find the workspace in the left sidebar
3. Click "Manage Workspace"
4. Click "Manage Billing" (opens Stripe)
5. If prompted, enter your email—Stripe will send you a login link
6. Scroll to the bottom to view your invoice history
7. Click any invoice date to open it, then download the PDF
Check your spam folder if the Stripe email doesn't arrive within a few minutes.
**Questions?** [Contact support](https://forms.rive.app/support?utm_medium=support_page).
# Trouble Logging In
Source: https://rive.app/docs/account-admin/account-overview/trouble-logging-in
## "Invalid credentials" error
Two common causes:
**1. You signed up with Google or Facebook** If you created your account using Google or Facebook login, we don't have a password stored—that's managed by them. Use the Google or Facebook sign-in button instead of email/password.
**2. Wrong password** Click "Forgot password?" below the login button. We'll email you a reset link.
**Questions?** [Contact support](https://forms.rive.app/support?utm_medium=support_page).
# Bring Your Own S3 Bucket
Source: https://rive.app/docs/account-admin/bring-your-own-bucket
Configure your own AWS S3 bucket to work with Rive
> [!NOTE]
>
> This feature is available exclusively to Enterprise plan customers. If you're interested in upgrading to unlock this capability, [contact us](https://rive.app/enterprise?utm_source=docs\&utm_medium=content).
## What is a custom S3 bucket?
A custom S3 bucket allows Enterprise customers to store their Rive file and asset data in their own AWS environment instead of Rive's default storage. This premium feature gives you greater control over your data, allowing you to:
* Apply your organization's security and compliance policies
* Keep data within your existing AWS infrastructure
* Integrate with your existing backup and disaster recovery processes
* Monitor and audit all access to your bucket using CloudTrail
If you have existing data in Rive that you would like migrated to your custom S3 bucket after upgrading to Enterprise, our team can help coordinate the migration process.
## Configuration
**1. Create an S3 bucket in your AWS Account**
Follow the [AWS documentation](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html) to create a new S3 bucket:
* Choose a unique name for your bucket \
**Note:** Use that name in place of `BUCKET_NAME` for the rest of this document
* Configure basic bucket settings
* Block public access
* You can choose to leave everything as default or you can decide to enable or customize:
* versioning (disabled by default)
* encryption - by default buckets and new objects are encrypted by Amazon's S3 managed keys (SSE-S3) which uses AES256
* tags
**2. Create an IAM Policy**
* In the AWS Console, under IAM / Policies click on *"Create policy"*
* Select the *"JSON"* Policy Editor view and paste the following:
```json theme={null}
{
"Statement": [
{
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject",
"s3:ListBucket",
"s3:GetBucketLocation",
"s3:AbortMultipartUpload",
"s3:ListBucketMultipartUploads",
"s3:ListMultipartUploadParts"
],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::BUCKET_NAME",
"arn:aws:s3:::BUCKET_NAME/*"
]
}
],
"Version": "2012-10-17"
}
```
**3. Create a new IAM Role**
* In the AWS Console, under IAM / Roles click on *"Create role"*
* Under *"Trusted entity type"* pick *"Custom trust policy"*
* In the JSON editor that appears paste the following:
```json theme={null}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "REQUEST_FROM_RIVE"
},
"Action": "sts:AssumeRole"
}
]
}
```
**Note:** You will need to request the appropriate value to replace `REQUEST_FROM_RIVE` from your Rive representative
* Hit *"Next"* to go to the *"Add permissions"* section
* Under *"Permission policies"* search for the IAM Policy you just created and select it
* Click *"Next"* to go to *"Name, review, and create"*
* Choose a name, review the trust policy and the permissions, and click *"Create role"*
* Open the Role you just created and make note of the ARN
**4. Provide Information to Rive**
Share the following information with your Rive representative:
* **Region**: Region of the S3 Bucket
* **Bucket Name**: Name of the Bucket
* **Role ARN**: ARN of the role you created
After providing all the above to your Rive representative, our team will configure your account to use your custom S3 bucket.
You'll receive a confirmation once everything is set up, at which point all your Rive resources will automatically be stored in your own S3 bucket.
## Troubleshooting
If you encounter issues with your S3 bucket configuration:
* Verify the IAM Role has the correct trust relationship (using the value provided by Rive)
* Ensure the IAM Policy has the necessary S3 permissions
* Check that your bucket is in the same region you provided to Rive
* Contact your Rive representative for additional assistance
# Pricing
Source: https://rive.app/docs/account-admin/pricing
For full details and feature comparison, see [rive.app/pricing](https://rive.app/pricing?utm_source=docs\&utm_medium=content).
## Plans
| Plan | Monthly | Annual (paid upfront) | Best for |
| :- | :- | :- | :- |
| **Free** | \$0 | \$0 | Learning Rive, personal projects |
| **Cadet** | \$17/seat/mo | \$108/seat/year | Small teams shipping to production (3 seats max) |
| **Voyager** | \$49/seat/mo | \$384/seat/year | Teams needing Libraries and collaboration (25 seats max) |
| **Enterprise** | — | \$1,440/seat/year | Large organizations (\$10M+ annual revenue) |
Annual billing saves money but requires full payment upfront.
## What's included
**Free**
* Exports for runtime, with a Rive splash screen
* 3 collaborative files
* State Machines, Data Binding, Scripting
* [Rive CLI](/docs/cli/monthly-allowance): 50 publishes and pushes a month, combined
**Cadet** (everything in Free, plus)
* Exports for runtime without the splash screen
* Unlimited files
* [Rive CLI](/docs/cli/monthly-allowance): 500 publishes and pushes a month, combined
**Voyager** (everything in Cadet, plus)
* Libraries
* [Rive CLI](/docs/cli/monthly-allowance): 5,000 publishes and pushes per seat a month, shared across the Workspace, with more through top-up credits
* CDN asset hosting
* Embed link hosting
* \$20/seat monthly agent credits
* Priority Community support
**Enterprise** (everything in Voyager, plus)
* Dedicated Slack with Rive team
* SSO and SOC2 Type II
* Custom S3 bucket
* Subteam Workspaces
* Org-wide permissions
* Onboarding and training
* Custom runtime support
* Long-Term Support (LTS) agreements
* Centralized billing
* [Rive CLI](/docs/cli/monthly-allowance): custom allowance
* \$40/seat monthly agent credits
***
## Legacy pricing
If you're on a legacy plan, your pricing is locked in as long as your plan stays active. Adding users may move you to current pricing. If your plan cancels, legacy pricing cannot be reinstated.
***
## Students
Rive offers a discounted Student Plan for individual students with a valid student email or documentation. The Student Plan is for personal educational work only—not for commercial use or team collaboration. Complete [this form](https://forms.rive.app/education?utm_medium=support_page) to request access to the Student Plan.
Schools, universities, and non-profits should use a standard Cadet or Voyager plan.
***
**Questions?** [Contact support](https://forms.rive.app/support?utm_medium=support_page).
# Managing Workspace Members
Source: https://rive.app/docs/account-admin/workspaces/managing-workspace-members
Add, remove, and change the roles of members in a workspace.
## Member roles
| Role | What they can do | Cost |
| :- | :- | :- |
| **Viewer** | View files only | Free |
| **Editor** | View and edit files | Paid seat |
| **Admin** | View, edit, and manage members | Paid seat |
## Inviting members to a workspace
Inviting a member to a workspace gives them access to all projects in that workspace.
> [!NOTE]
>
> If you only want to give a member access to a specific project, open that project and invite them from the right sidebar.
**Step 1**
Go to [rive.app/account](https://rive.app/account?utm_source=docs\&utm_medium=content).
**Step 2**
Click **Manage Workspace** next to the workspace you want to add a member to.
**Step 3**
Under **Members**, click **Invite Members**.
**Step 4**
Enter the member's email address, select their role, and click **Confirm**.
> [!NOTE]
>
> For paid workspaces, you're charged a prorated amount immediately for each Editor or Admin seat.
## Accepting an invite to a workspace
**Step 1**
Go to [rive.app/account](https://rive.app/account?utm_source=docs\&utm_medium=content) and make sure you're logged in to the correct Rive account.
**Step 2**
Follow the invite link in your email.
## Changing member roles
**Step 1**
Go to [rive.app/account](https://rive.app/account?utm_source=docs\&utm_medium=content).
**Step 2**
Click **Manage Workspace** next to the workspace you want to update.
**Step 3**
Under **Members**, click **Manage Roles**.
**Step 4**
Select the new role and click **Confirm**.
> [!NOTE]
>
> For paid workspaces, you're charged a prorated amount immediately for each Editor or Admin seat.
## Removing members from a workspace
Admins can remove members from a workspace at any time.
**Step 1**
Go to [rive.app/account](https://rive.app/account?utm_source=docs\&utm_medium=content).
**Step 2**
Click **Manage Workspace** next to the workspace you want to update.
**Step 3**
Under **Members**, click the **x** next to the member you want to remove.
> [!NOTE]
>
> The workspace owner can't be removed. If you need to change ownership, [contact support](https://forms.rive.app/support?utm_medium=support_page).
## FAQs
> [accordion] Why can't I invite or remove a member?
>
> Make sure your email address is verified. Go to [rive.app/account](https://rive.app/account?utm_source=docs\&utm_medium=content), open the **Profile** tab, and click **Resend verification email** if needed.
> [accordion] Why do we both have to pay to collaborate? We both have paid workspaces.
>
> Rive charges per seat per workspace. If you're an Editor in multiple workspaces, each workspace pays for your seat separately. To collaborate, one of you should invite the other to their workspace, and that workspace pays for the seat.
> [accordion] Why can't I find the invite email?
>
> Check your spam folder and make sure the invite was sent to the correct email address.
# Managing Workspaces
Source: https://rive.app/docs/account-admin/workspaces/managing-workspaces
Create, upgrade, transfer, and delete workspaces.
## Workspace admin
The workspace admin lets you:
* View your current AI credit usage and purchase more
* View and invite members to the workspace
* View projects in your workspace
To view the workspace admin, go to the editor **Home** tab, open the dropdown next to the workspace name, and select **Admin**.
## Creating a new workspace
Create a new workspace when you want a separate space for a team or project.
> [!NOTE]
>
> Workspaces are separate spaces for files, members, and billing. If you only want to organize files or share a specific set of files, create a new project instead.
**Step 1**
From the Editor home screen, open the workspace dropdown and select **+ New Workspace**.
**Step 2**
Choose a workspace name, invite members, and click **Create**.
> [!NOTE]
>
> You can add or remove members from Workspace Settings later.
You should now see an empty workspace with a **Personal** project. You can create files in this workspace.
## Upgrading a workspace
For more information about plans and features, see [Pricing](https://rive.app/pricing?utm_source=docs\&utm_medium=content).
> [!NOTE]
>
> Each workspace is billed separately. Make sure you upgrade the workspace where you want to use the paid features.
**Step 1**
Go to [rive.app/account](https://rive.app/account?utm_source=docs\&utm_medium=content).
**Step 2**
Click **Manage Workspace** next to the workspace you want to upgrade.
**Step 3**
Click **Upgrade Plan**.
**Step 4**
Select a plan and billing option.
**Step 5**
Follow the checkout steps to complete your payment.
## Transferring workspace ownership
**Step 1**
Make sure the new owner is already a member of the workspace and has the Admin role. See [Inviting Workspace Members](/docs/account-admin/workspaces/managing-workspace-members#inviting-members-to-a-workspace) and [Changing Member Roles](/docs/account-admin/workspaces/managing-workspace-members#changing-member-roles).
**Step 2**
[Contact support](https://forms.rive.app/support?utm_medium=support_page) with:
* The workspace name
* The email address of the current owner
* The email address of the new owner
We'll handle the transfer for you.
## Deleting a workspace
> [!NOTE]
>
> If you want to cancel your plan without permanently deleting your files, see [Cancel Your Plan](/docs/account-admin/account-overview/cancel-my-account).
To permanently delete a workspace for all members, including all files in the workspace, see [Deleting a Workspace](/docs/home/account-admin/workspaces/delete-a-workspace).
## FAQs
> [accordion] I upgraded, but my workspace still says it's free.
>
> You probably upgraded a different workspace. Use the workspace switcher to find your paid workspace.
> [accordion] I upgraded one workspace. Why aren't all my workspaces paid?
>
> Each workspace is billed separately. Upgrading one workspace doesn't affect the others.
> [accordion] My plan lapsed and now the price is higher. Can I get my old price back?
>
> If you had legacy pricing, it was locked in as long as your plan stayed active. Once canceled, we can't reinstate it. You'll need to upgrade at the current price.
# Reactivating a Canceled Plan
Source: https://rive.app/docs/account-admin/workspaces/reactivating-a-canceled-workspace
If your workspace was canceled but not deleted, you can reactivate it.
1. Go to [rive.app/account](https://rive.app/account?utm_source=docs\&utm_medium=content)
2. Find the canceled workspace in the left sidebar (status shows "Suspended")
3. Click "Manage Workspace"
4. Click "Reactivate Plan"
5. Select monthly or yearly billing
6. Click "Confirm & Pay"
Your workspace is now active again.
***
## ⚠️ Don't create a new workspace by mistake
"Create new Workspace" is **not** the same as reactivating. If you have multiple workspaces, double-check you're reactivating the right one—each workspace has a display name and a username.
**If you accidentally created a new workspace instead of reactivating:** [Contact support](https://forms.rive.app/support?utm_medium=support_page). We can cancel the incorrect workspace and refund you, but we can't transfer payments or files between workspaces. If you saved files in the wrong workspace, download your backups (.rev files) before we cancel it.
**Questions?** [Contact support](https://forms.rive.app/support?utm_medium=support_page).
# Workspaces
Source: https://rive.app/docs/account-admin/workspaces/workspaces-overview
Workspaces are separate areas in Rive for organizing files and collaborating with others.
**Each workspace is isolated from the others. It has its own projects, files, members, roles, permissions, AI credits, and billing plan.**
For example, you might have:
* A personal workspace for your own files
* A company workspace for your team’s files
* A client's workspace that you've been invited to
> [!NOTE]
>
> Workspaces are separate spaces for files, members, and billing. If you only want to organize files or share a specific set of files, create a new project instead.
## Switching workspaces
To view or work with files in another workspace, go to the editor Home tab, click the dropdown next to the workspace name, and hover over Switch Workspace.
## Workspace admin
To open the workspace admin, go to the editor **Home** tab, click the dropdown next to the workspace name, and choose **Admin**. It has four tabs:
* **Overview** - AI Agent credits and workspace details: name, plan, status, and member counts. Editor and viewer counts include external members who have access to files in this workspace.
* **Members** - everyone in the workspace and their role, plus external members.
* **Projects** - all projects in the workspace, including archived ones you can restore.
* **Options** - editor defaults that apply to everyone in the workspace, such as view model naming conventions and whether new data binds are relative. Only admins can change them.
Admins also see a button in the header:
* **Upgrade Workspace** - on a free workspace, move it to a paid plan. Opens in your browser. See [Upgrading a workspace](/docs/account-admin/workspaces/managing-workspaces#upgrading-a-workspace).
* **Manage Workspace** - on a paid workspace, open billing, plan, and workspace settings in your browser.
### External members
External members are people outside the workspace who have access to individual files. They're listed at the bottom of the **Members** tab. Admins can remove an external member, which revokes all of their file access in the workspace.
### Leaving a workspace
To remove yourself from a workspace, open the workspace admin and click **Leave Workspace** below the workspace details. You lose access to its projects and files. The workspace owner can't leave the workspace.
## FAQs
> [accordion] Why can't I find my Rive file
>
> Rive files live in the workspace they were created in or shared with. Try looking for it in a [different workspace](/docs/account-admin/workspaces/workspaces-overview#switching-workspaces).
# Working with AI Agents
Source: https://rive.app/docs/cli/agents
Pair the Rive CLI with Claude Code, Cursor, or your agent of preference.
Pair the Rive CLI with a coding agent to create and iterate on Rive graphics using natural language. The agent can write RML, scripts, and shaders directly in your project while you watch the result update in the live preview.
Each Rive project includes instructions that teach coding agents how to work with Rive. Your agent can use the CLI to look up Rive types and properties, compile and inspect its work, and render screenshots to check the result. This gives the agent the context and feedback it needs to make changes without you having to specify the underlying RML.
## Setting up
**1. Create a project**
```bash theme={null}
rive create myproject
```
`rive create` writes an `AGENTS.md` and `CLAUDE.md` into the folder. Agents read this when
they open the directory, and it tells them how to look up the CLI reference and
how to check their work.
**2. Start the preview window**
```bash theme={null}
rive myproject
```
Leave this running in its own terminal. It rebuilds and reloads on every save, so
you watch the scene change as the agent edits it.
**3. Open the folder in your agent**
Open `myproject` in Claude Code, Cursor, or any agent that can read and write
files and run shell commands. No further setup is needed.
**4. Describe what you want**
Prompt the agent in plain language. It reads `AGENTS.md`, looks up the types it
needs with `rive docs` and `rive schema`, writes the RML and Luau, then checks the
result with `rive
--verify` and `rive inspect --summary`, the two checks
`AGENTS.md` tells it to run. Ask for a `rive --screenshot` when you want to
see it.
> Build a weather card: a rounded panel with the city name, a temperature
> readout, and an icon that animates when it rains. Bind the temperature to a
> view model property so the host app can set it.
> [!TIP]
>
> Ask the agent to work in stages rather than building everything at once. Start with a wireframe, then add structure, content, and detail. This makes layout and sizing problems easier to catch early and gives you opportunities to redirect the agent as it works.
## CLI vs AI Agent
Rive also has an AI Agent built into the Editor. To compare the two, see [AI Agent vs CLI](/docs/editor/ai/agent-vs-cli).
# Examples
Source: https://rive.app/docs/cli/examples
Sample projects, headless rendering, and running the CLI in CI.
## Sample projects
The CLI ships a number of example projects. `rive samples` opens a picker and copies the
one you choose into a directory you name:
| Sample | Shows |
| - | - |
| `rml_triangle` | The smallest RML document: one artboard, one shape |
| `rml_vm_input` | RML driven by view model data, with a script input |
| `rml_split` | The same scene split across files: view models in `data/`, referenced by id from the scene |
| `hello_rive` | The smallest layout script: draw a moving shape each frame |
| `pointer_reactive` | Making a scene follow the mouse: pointer to view model to data bind |
| `input_demo` | Keyboard, text and gamepad events in a script |
| `keyboard_menu` | A keyboard-driven menu with no script: named key filters on a focus node, view model triggers driving a state machine |
| `text_input` | Editable text fields via the TextInput component: placeholder, obscured entry, Tab traversal |
| `scroll_demo` | Wheel and trackpad scrolling, with a horizontal strip nested inside a vertical list |
| `vm_debug` | Every view model property type driven by a script, plus a click listener writing one natively |
| `remote_artboard` | Downloading a `.riv` and binding its artboard to a view model property. Run with `--allow-net` |
| `scripted_text` | Fonts and shaped text from a script: a wrapped bilingual paragraph, a caret with its selection, animated glyphs |
| `cursor_demo` | Asking the window for an OS cursor: hand over a button, resize across a drag |
| `tests_demo` | Luau unit tests, run with `--test` |
Each directory is a project in its own right. Where no picker can draw, as in CI,
`rive samples` prints the list with descriptions and a ready `cp` line:
```bash theme={null}
cp -R "$(rive samples --path)/rml_triangle" myproject
rive myproject
```
## Headless rendering
`--screenshot` builds the project, renders one frame without opening a window, and
writes a PNG. It needs no login, which makes it the check to run in CI.
```bash theme={null}
rive myproject --screenshot=out.png # before anything advances
rive myproject --screenshot=out.png --advance=1s # one second in
rive myproject --screenshot=out.png --viewport=390x844 # at a specific size
```
> [!NOTE]
>
> A capture with no `--advance` is the authored rest pose, not the animation's opening
> frame, because the state machine has not run yet. Start previews at `--advance=1`.
> [!NOTE]
>
> `--screenshot` resolves its path against the current directory, not the project
> directory, and a missing directory fails with only `screenshot failed: `.
> Create the directory first.
## Driving a scene
A screenshot of a resting scene tells you nothing about whether it responds to
anything. Two flags drive it before the capture.
`--data` sets a view model property. The path is relative to the instance bound to
the artboard, and each segment is a property name:
```bash theme={null}
rive myproject --screenshot=full.png --data=battery/level=100
```
`--pointer` simulates a pointer at artboard coordinates. `click` is a move, a press
and a release with a frame between each, because a state machine only sees a gesture
when it next runs:
```bash theme={null}
rive myproject --screenshot=hover.png --pointer=move@120,60
rive myproject --screenshot=on.png --pointer=click@120,60 --advance=20
```
Both flags repeat, so you can set several values or play a sequence of gestures.
> [!NOTE]
>
> Quote a `drag` value. The `>` between the two points is a shell redirection
> otherwise:
>
> ```bash theme={null}
> rive myproject --screenshot=scrolled.png --pointer='drag@200,300>200,80:12'
> ```
Tip
**Example - Proving a Toggle Works**
Capture the control at rest, after one click, and after two. `rest` and `on` must
differ, or the control does nothing. `off` must match `rest`, or it only works one
way.
```bash theme={null}
rive myproject --screenshot=rest.png
rive myproject --screenshot=on.png --pointer=click@120,60 --advance=20
rive myproject --screenshot=off.png --pointer=click@120,60 --advance=1 \
--pointer=click@120,60 --advance=20
```
Add `--compare=rest.png` to the later captures and the CLI prints how many pixels
differ, so the check is a number rather than a judgement. `--probe=` prints the
color at one point as `AARRGGBB`, which is enough to assert a single state.
Put an `--advance` between two clicks on the same control, as above. A value a
listener writes is not visible to the next listener until a frame has passed, so
back-to-back clicks can both act on the old value.
## Checking responsiveness
A layout tree and a hand-positioned screen look identical in a single screenshot.
Shoot the same file at two sizes and see whether anything moved:
```bash theme={null}
rive myproject --screenshot=wide.png --viewport=900x600
rive myproject --screenshot=narrow.png --viewport=320x700
```
`--viewport` resizes the artboard itself, rather than scaling or cropping what it
renders. Layouts reflow into the new size, which is what makes this a real
responsiveness check. Content at fixed coordinates stays where it is, so a design
with no layout components looks cropped at a smaller viewport and gains empty space
at a larger one.
## In CI
`--verify` compiles everything and writes nothing. `--test` runs the project's Luau
tests. Both exit non-zero on failure, and `--format=json` gives you one JSON object
on stdout with logs kept on stderr:
```bash theme={null}
rive myproject --verify --format=json
rive myproject --test --format=json
```
Each kind of failure has its own exit code, so a pipeline can branch without parsing
output. See [Exit Codes](/docs/cli/reference/commands#exit-codes).
> [!NOTE]
>
> Publishing needs a browser sign-in, which a CI runner usually cannot do. Every other
> mode works there. You can author, compile, test and capture in CI, then publish from
> a machine that is signed in.
## Measuring performance
`--bench` builds the project, times a number of frames without opening a window, and
reports advance and render statistics along with WASM memory growth:
```bash theme={null}
rive myproject --bench=600
```
# Getting Started
Source: https://rive.app/docs/cli/getting-started
Install the Rive CLI and build your first project.
Install the Rive CLI, create a project, and open the live preview. By the end of this guide, you'll have a `.riv` file you can load with the Rive Runtimes.
**1. Install the CLI**
The CLI runs on macOS with Apple Silicon, on Linux x86_64, and on Windows.
> [tab] Installer
>
> ```bash theme={null}
> curl -fsSL https://releases.rive.app/cli/install.sh | sh
> ```
>
> Add the CLI to your `PATH` so the `rive` command is available in every new
> shell, then reload your current shell to pick it up:
>
> ```bash theme={null}
> echo 'export PATH="$HOME/.rive/bin:$PATH"' >> ~/.zshrc
> source ~/.zshrc
> ```
> [tab] Windows
>
> ```powershell theme={null}
> irm https://releases.rive.app/cli/install.ps1 | iex
> ```
> [tab] Homebrew
>
> ```bash theme={null}
> brew install --cask rive-app/tap/rive-cli
> ```
>
> `rive update`, `rive switch` and `rive uninstall` need the installer build
> under `~/.rive`, so they do not work with a Homebrew install. Manage a
> Homebrew install with `brew` instead, using `brew upgrade` and
> `brew uninstall --cask rive-cli`.
Run `rive doctor` to check your install.
**2. Create a project**
```bash theme={null}
rive create myproject
```
That writes a `rive.yaml`, an `AGENTS.md` and `CLAUDE.md` for coding agents, a
`.gitignore`, and
a `scene.rml` holding the same frame the Editor gives a new file: an artboard, a
timeline, and a state machine that plays it on load. A shape you add and key
starts animating without any further setup.
Everything else you drop in the folder is picked up by extension: `.luau`
scripts, `.wgsl` shaders, images and fonts. The generated `rive.yaml` sets `name`
and turns the build logs on; everything else in
[rive.yaml](/docs/cli/reference/project-config) is optional.
**3. Open the preview window**
```bash theme={null}
rive myproject
```
This opens a window showing the scene and watches the directory. Save any file
and it rebuilds and reloads, writing `myproject/build/myproject.riv`, the file
you can load with a [runtime](/docs/runtimes/getting-started).
A new project has nothing drawn in it yet, so you get a dark rectangle. Keep this
running in one terminal while you edit in another.
To build without opening a window, use `rive myproject --publish`, which creates a signed `.riv`. To check that the
project compiles without writing anything, use the `--verify` flag instead.
## Starting from a file in your Rive account
If the work already exists in your Rive account, download it into a project:
```bash theme={null}
rive create myproject --from-remote-file
rive myproject
```
The CLI lists your projects and files to pick from, and `rive ls` prints the same ids
non-interactively when you need them for a script. `rive.yaml`
records the link, so [`rive push`](/docs/cli/reference/project-config#pushing-to-a-rive-file)
sends your edits back and `rive pull` brings down changes made in the Editor. This
requires a logged in session with `rive login`.
## Starting from an exported .rev
You can also convert a `.rev` exported from the Editor, which doesn't require a logged in session:
```bash theme={null}
rive create myproject --from-rev=myfile.rev # --from-rev takes a path to the .rev
rive myproject
```
The scene comes out as `scene.rml`, and every script, shader and asset is written as
its own file, laid out the way the Editor's **Assets** panel had them. You also get
the usual `rive.yaml`, `AGENTS.md` and `.gitignore`, so it is an ordinary project
from that point on.
The project name has to be empty or new. Omit it and the `.rev`'s own name is used, so
`myfile.rev` becomes `myfile/`.
## Signing in
You don't need to sign in to create, preview, or build projects locally. Sign in when you need to publish a file or export a `.rev` to open in the Rive Editor:
```bash id="bmt6er" theme={null}
rive login
```
An account is required for `--publish`, which signs the file through Rive's API, and `--rev`, which exports a `.rev`. Everything else runs locally and works signed out and offline.
If you aren't a member of any Workspace, the CLI also creates a Free Workspace for you
when you sign in. Publishes from projects that aren't
[bound to a file](/docs/cli/reference/project-config#pushing-to-a-rive-file) then count
against it, because it's the only Workspace where you're an Editor.
> [!WARNING]
>
> A file containing scripts that is destined for the web must be built with
> `--publish`. Unsigned scripts are rejected by the CDN and the web runtimes. A file with no scripts is unaffected.
`--publish` writes a `.riv` with no watermark when the Workspace the publish counts
against is on the [Cadet plan or higher](https://rive.app/pricing). Otherwise it adds
a watermark. A project bound to a file with
[`rive push`](/docs/cli/reference/project-config#pushing-to-a-rive-file) counts against
the file's Workspace. Other projects count against the Workspace you choose with
[`rive workspace`](/docs/cli/reference/commands#workspace), or the only one where you're an
Editor. See
[Which Workspace counts](/docs/cli/monthly-allowance#which-workspace-counts).
## Exporting your project
Once you're ready to share or export your CLI project, there are a few ways you can proceed:
| You want to | Export | Command |
| - | - | - |
| Keep working on it in the Rive Editor | A file in your Rive account, or a `.rev` | `rive push`, or `--rev` |
| Load it in your app with a Rive runtime | A `.riv` | `--publish` |
### Pushing to the Rive editor
To open the project in the Editor, push it to a file in your Rive account:
```bash theme={null}
rive login # once per machine
rive push myproject # the first push asks which Rive project to create the file in
```
The file shows up in the Editor's file browser like any other, and `rive.yaml` records
the link so later pushes update the same file. Bring changes made in the Editor back into
the project with `rive pull`. See
[Pushing to a Rive file](/docs/cli/reference/project-config#pushing-to-a-rive-file) for how
pushes, revisions and conflicts work.
If you'd rather export a `.rev`:
```bash theme={null}
rive myproject --rev=myproject.rev
```
Both `rive push` and exporting a `--rev` require a logged in session from the CLI.
### Build a .riv for the runtimes
To load the project in your app, build a `.riv` and add it to your project like any
other Rive file:
```bash theme={null}
rive myproject --publish # signed .riv, needs rive login
```
This writes to `myproject/build/myproject.riv`, or to the directory set by
[`output.dir`](/docs/cli/reference/project-config#keys) in `rive.yaml`. From there, follow
the [runtime guide](/docs/runtimes/getting-started) for your platform to load it.
> [!TIP]
>
> To share a playable link instead of a file, `rive myproject --publish=web` hosts the
> build as a public page. See [Publishing CLI Projects](/docs/cli/publishing).
## More resources
* [RML](/docs/runtimes/advanced-topic/rml) - the markup that describes a scene
* [AI Agents](/docs/cli/agents) - hand the project to Claude Code or Cursor
* [Examples](/docs/cli/examples) - sample projects to start from, rendering without a window, and CI
* [Commands](/docs/cli/reference/commands) - every command and flag
# Monthly CLI Allowance
Source: https://rive.app/docs/cli/monthly-allowance
How many publishes and pushes each plan includes per month, what counts, and what happens at the limit.
Free, Cadet, Voyager, and Enterprise each include a monthly allowance of Rive CLI
publishes and pushes for each Workspace. Three actions count: `rive push`, `--publish`, and
`--publish=web`.
Building and previewing on your own machine and exporting from the Rive Editor are
unlimited and never count against the allowance.
## Allowance by plan
| Plan | Allowance per Workspace, per month |
| - | - |
| Free | 50 publishes and pushes, combined |
| Cadet | 500 publishes and pushes, combined |
| Voyager | 5,000 publishes and pushes per seat, combined and shared across the Workspace. Top-up credits cover more. |
| Enterprise | Set in your agreement |
Student plans and legacy paid plans have no monthly allowance. See
[Pricing](/docs/account-admin/pricing) for what else each plan includes.
## Which Workspace counts
Each action counts against one Workspace. That Workspace's plan decides the allowance
and whether a publish has the watermark (the Rive splash screen).
* **A push** counts against the Workspace that owns the Rive file it pushes to.
* **A publish from a project bound to a Rive file** (`push.fileId` in
[`rive.yaml`](/docs/cli/reference/project-config#pushing-to-a-rive-file)) counts against
the Workspace that owns the file. You need edit access to that file.
* **A publish from a project that isn't bound to a file** counts against the Workspace
you choose with [`rive workspace `](/docs/cli/reference/commands#workspace). If you
haven't chosen one, it counts against the only Workspace where you're an
[Editor](/docs/account-admin/workspaces/managing-workspace-members#member-roles).
* **A web publish from a project that isn't bound to a file** counts against the
Workspace that owns the page. See [Publishing CLI Projects](/docs/cli/publishing).
To publish a project that isn't bound to a file, you need to be an Editor in the
Workspace it counts against. Admins count as Editors, and Viewer access isn't enough.
Without the Editor role, the CLI stops and says why, and nothing counts.
If you aren't a member of any Workspace, the CLI creates a Free Workspace for you,
right after `rive login` signs you in, or when you next run a command that needs a
Workspace. You're its admin, and it's the only Workspace where you're an Editor, so
publishes from projects that aren't bound to a file count against it.
[`rive workspace`](/docs/cli/reference/commands#workspace) explains how the new Workspace
gets its name.
If you're a Viewer in one or more Workspaces but an Editor in none, a publish from a
project that isn't bound to a file stops. Ask an admin of one of those Workspaces for
the Editor role, or create your own Free Workspace with
[`rive workspace create `](/docs/cli/reference/commands#workspace).
If you haven't chosen a Workspace and you're an Editor in several, a publish from a
project that isn't bound to a file stops before anything counts. A web publish doesn't
need this choice, because it uses the page's Workspace. When the CLI stops, it lists the
Workspaces where you're an Editor and exits with code `10`:
```text theme={null}
Choose the Workspace this publish counts against with `rive workspace `.
77 Client Work
2201 Acme Studio
```
Run `rive workspace 2201` to choose Acme Studio, then publish again. The CLI saves the
choice for later publishes from projects that aren't bound to a file.
With `--publish --format=json`, the top-level `workspace` field names the Workspace the
publish counts against, or is `null` when Rive doesn't name one. It has `id`, `name`,
`personal`, and `admin` (`true` when you can upgrade it). When the publish counts
against your account instead of a Workspace, `personal` is `true` and `name` is `null`.
> [!NOTE]
>
> Older versions of the CLI don't send your chosen Workspace with a publish. For them, a
> publish from a project that isn't bound to a file counts against the only Workspace
> where you're an Editor. If you're an Editor in several Workspaces or in none, it counts
> against your account instead of a Workspace. If you're an Editor in several, update the
> CLI and choose one.
## What counts
Each action counts once:
| Action | Counts when |
| - | - |
| `rive push` | The push completes |
| `--publish` or `--publish=local`, which writes the `.riv` to disk | The publish starts |
| `--publish=web`, which publishes a hosted page | The publish starts |
A `.riv` you publish to test on your own machine counts like any other publish.
A web publish counts once, as a publish. Uploading and hosting the page do not count
separately.
A publish counts as soon as it starts, even if a later step such as signing fails.
A push counts only when it completes, so a push that fails does not count.
## What never counts
* Exports from the Rive Editor, on any plan.
* `rive pull`, on any plan.
* `rive build`, which ships the project as an Android or iOS app, on any plan.
* Work that stays on your machine: the preview window that rebuilds as you edit,
`--serve`, `--verify`, `--test`, `--screenshot`, and `rive inspect`. These make no
calls to Rive.
* `--rev`. It needs `rive login`, but it does not count.
* A push that fails, and a push that finds the file already up to date.
* Retries and status checks the CLI makes on its own during one action. Running the
command again is a new action.
## Monthly reset
The allowance resets at 00:00 UTC on the first day of each month. Actions you do not
use in a month do not carry over to the next month.
## Warning before the limit
When 20% or less of the allowance is left, the CLI prints one warning per run. The
warning shows the Workspace, how many actions are left, and when the allowance resets:
```text theme={null}
CLI allowance in Acme Studio: 8 of 50 publishes and pushes left this month (resets Dec 1). Upgrade: https://rive.app/pricing
```
Admins of that Workspace get the link to upgrade. In its place, everyone else gets
"Ask an admin of Acme Studio to upgrade."
With `--publish --format=json`, the warning is in `warnings`.
## Past the allowance on Voyager
When a Voyager Workspace uses up its monthly allowance, CLI publishes and pushes
continue on the Workspace's top-up credits, the same credits the Rive Agent uses.
Each action uses \$0.01 in credits. The CLI tells you and your agent when an action
was paid with credits and how much is left. When the credits run out, the CLI stops
and links to where you can top up.
## When the allowance is used up
The CLI checks the allowance before a push starts. A push that fails this check sends
nothing.
The CLI stops the action and does not retry it. It prints the reset date and how to
upgrade, and exits with code `9`:
```text theme={null}
Monthly CLI allowance used up in Acme Studio: 50 of 50 publishes and pushes. Resets Dec 1, 2026 (UTC). Upgrade: https://rive.app/pricing
```
The message names the Workspace the action counts against. Admins of that Workspace
get the link to upgrade. In its place, everyone else gets
"Ask an admin of Acme Studio to upgrade."
If the message names a Workspace you didn't expect,
[Which Workspace counts](#which-workspace-counts) explains how the CLI picks it and how
to change it.
With `--publish --format=json`, the message is in `errors`. The same answer is also in
the `allowance` field, with `code`, `message`, `scope`, `limit`, `used`, `resetsAt`,
`upgradeUrl`, and `workspace`. That `workspace` has the same `id`, `name`, `personal`,
and `admin` fields as the top-level `workspace` field. `allowance` is `null` unless the
allowance stopped the run.
Files you already pushed or published keep working. You can still pull, preview,
check builds with `--verify`, build apps, and export from the Rive Editor. To publish
or push from the CLI again before the reset, [upgrade the Workspace](https://rive.app/pricing)
or, on Voyager, use top-up credits.
> [!NOTE]
>
> The monthly allowance is separate from the short-term rate limits on publishing,
> which apply on every plan. See [Publishing CLI Projects](/docs/cli/publishing).
# Rive CLI
Source: https://rive.app/docs/cli/overview
Create, preview, inspect, and publish Rive graphics from the command line, without opening the Editor.
The Rive CLI brings Rive into your terminal. Build `.riv` files for your app or game and `.rev` files that open in the Rive Editor, with a live preview running locally as you work.
Pair the CLI with your coding agent of choice to build a scene from scratch, or modify and inspect an existing Rive graphic from your account. You describe the graphic, the agent writes the scene in [Rive Markup Language (RML)](/docs/runtimes/advanced-topic/rml), and you watch the result take shape and steer it as it goes.
```bash theme={null}
rive create myproject # scaffold a project
rive myproject # preview window, rebuilds as you edit
```
[YouTube video player](https://www.youtube.com/embed/G2TGQF57eoY)
## What it enables
* **Build with RML.** Build entire Rive scenes using Rive Markup Language (RML). The CLI
parses this to compile a local preview, and can build `.riv` assets from it.
* **Check what you built.** Confirm a scene compiles, inspect what it actually
contains, and look up any type in the Rive object model.
* **Pair with a coding agent.** A new project comes with instructions an agent
reads, so it knows how to look things up and check its own work. See
[AI Agents](/docs/cli/agents).
* **Render and test without a window.** Capture frames as images, drive a scene
with simulated input and data, and run script tests
* **Keep your work in version control.** A project is a folder of text and assets,
so it diffs and reviews with the rest of your code.
* **Work with files in your Rive account.** Browse your Workspace with `rive ls`,
download a file into a project with `rive create --from-remote-file`, send your edits
back with `rive push`, bring Editor changes down with `rive pull`, and open any file
in the Editor with `rive open`.
* **Put a scene on the web.** Deploy your Rive project as a
web page anyone can open. Rive hosts this so you don't have to.
To compare the CLI with the AI Agent built into the Editor, see [AI Agent vs CLI](/docs/editor/ai/agent-vs-cli).
# Publishing CLI Projects
Source: https://rive.app/docs/cli/publishing
Build, sign and host a CLI project as a page anyone can open, with nothing to host yourself.
`--publish=web` builds and signs a Rive project, and hosts it as a public page anyone
can open: one URL playing the built `.riv`. `--publish` on its own writes a signed `.riv` to disk.
```bash theme={null}
rive login # once per machine, the same session as --publish
rive myproject --publish=web # build, sign, upload, wait for it to go live
# published my-scene
# https://my-scene-k2f9qa.pages.rive.app
```
## Publish a page
**1. Login**
```bash theme={null}
rive login
```
Publishing needs a signed-in session, for the reason covered under
[signing and the web runtime](#signing-and-the-web-runtime).
**2. Choose a Workspace**
Pages belong to a Workspace. If you aren't a member of any Workspace, the CLI creates
a Free Workspace for you when you sign in, or when you next publish. To create another
Workspace, run [`rive workspace create `](/docs/cli/reference/commands#workspace).
You can also create a Workspace in the Rive Editor, or join an existing one.
If you're an [Editor](/docs/account-admin/workspaces/managing-workspace-members#member-roles)
in one Workspace, the CLI picks it for you. If you're an Editor in several, the CLI
opens a picker to select one. To skip the question, pass the Workspace ID with
`--workspace=`. `rive workspace` lists your Workspaces and their IDs.
`--team=`, the older name for this flag, still works.
**3. Publish**
```bash theme={null}
rive myproject --publish=web
```
The CLI builds the project, signs it, uploads it, waits for the page to go live,
and prints the public URL. The name comes from `--name=` if you pass one, then
`pages.name` once the project has published before, then the project's `name` in
`rive.yaml`. So renaming the project does not move an existing page.
The first publish records where the page lives by writing a `pages:` block into
`rive.yaml`. Later publishes leave it alone:
```yaml theme={null}
pages:
workspaceId: 77
name: "my-scene"
```
## Signing and the web runtime
A published page is played by the Rive web runtime, and web runtimes refuse unsigned scripts.
An unsigned build would load and then play nothing, so `--publish=web` always builds
the way `--publish` does.
The same watermark rule as `--publish` applies. A web publish from a project that isn't
bound to a file counts against the Workspace that owns the page, and that Workspace's
plan decides the watermark. See
[Which Workspace counts](/docs/cli/monthly-allowance#which-workspace-counts).
## Republish a page
A page is identified by its name within its Workspace. The name is lowercased into a slug
(anything outside `a-z0-9` becomes a dash), and the url is that slug plus a short
random suffix minted once, when the page is created.
Publishing the same name again replaces what the url serves. The url does not change,
so a link you handed out keeps working and starts showing the new build. Publishing a
different name creates a different page at a different url.
`--name=` on a later publish is a one-off: it publishes to that name without
changing the `pages:` block, so the project keeps pointing at its original page.
## Publish from CI
`--no-wait` prints the url and exits as soon as the upload is accepted, without
waiting for the page to go live. With `--quiet`, stdout is two lines: the name (with
its expiry date, if it has one) and then the url.
```bash theme={null}
set -euo pipefail
url=$(rive myproject --publish=web --no-wait --quiet | tail -1)
```
> [!WARNING]
>
> Set `pipefail` before piping the output. Without it the pipeline reports `tail`'s
> status rather than the CLI's, so a failed sign-in, build or upload exits `0` and the
> job carries on with an empty `url`.
Pass `--workspace=` as well, since the CLI can't ask which Workspace to use when
stdin is not a terminal.
> [!NOTE]
>
> Publishing is rate limited per account. A run that hits the limit reports
> `too many publishes for now`.
## Set how the control bar starts
A published page carries a small bar of controls for its fit, full screen, and copying
its url. The bar shows for a moment and then hides to a lip at the bottom of the page.
`--drawer=` changes how it starts:
| Mode | The page |
| - | - |
| `docked` | keeps the bar out |
| `hidden` | starts with only the lip showing |
| `none` | has no bar at all (paid plans) |
The first time the bar opens, a tooltip over its Rive link reads "Made with Rive. Build
your own." for a few seconds. On a page that starts with only the lip, the tooltip shows
above the lip first. On a paid plan, `--no-promo` leaves the tooltip off. If your
Workspace moves to a plan without these options, its pages show the tooltip and the
bar again, until you upgrade.
Each publish sends its own settings, so pass `--drawer=` and `--no-promo` every time you
publish the page.
## List published pages
List your published pages with the `list-published` command.
```bash theme={null}
rive myproject --list-published # where is this project published
rive myproject --list-published=web # every page in the Workspace, with its url
```
`built` means the file is on disk. `not published`
means no page was found for the project's `pages:` binding.
## Unpublish a page
```bash theme={null}
rive myproject --unpublish=web # take the project's page down
rive myproject --unpublish=web --name=prototype # take down a page by name
```
> [!WARNING]
>
> `--unpublish=web` has no undo. The url stops resolving, the files are removed, and the
> name frees up. Publishing that name again mints a new url, so the old link does not
> come back. The CLI asks for confirmation unless `--yes` is passed; in CI, where there
> is no terminal to confirm on, set this flag.
## Page expiry
On some plans, a page may expire after its first publish. When a page
has an expiry date, the publish prints it on its first line, in your own time zone:
```text theme={null}
published my-scene (expires 4 Oct)
https://my-scene-k2f9qa.pages.rive.app
```
Republishing a live page keeps its date. Once a page has expired, its url stays offline
and its name frees up, so publishing the name again makes a new page at a new url.
## Flags
| Flag | Does |
| - | - |
| `--publish=web` | Build, sign and publish the page |
| `--workspace=` | The ID of the Workspace that owns the page, instead of being asked |
| `--name=` | Publish under this name, instead of the project's |
| `--no-wait` | Print the url and exit without waiting for the page to go live |
| `--drawer=` | How the page's control bar starts: `docked`, `hidden` or `none`. `none` needs a paid plan |
| `--no-promo` | Leave the "Made with Rive" tooltip off the page. Needs a paid plan |
| `--list-published[=]` | Where this project is published. Bare prints `local` and `web`; `web` lists every page in the Workspace |
| `--unpublish=web` | Take the page down |
| `--yes`, `-y` | Skip the `--unpublish=web` confirmation |
# Command Reference
Source: https://rive.app/docs/cli/reference/commands
Every Rive CLI command, flag, and exit code.
```bash theme={null}
rive COMMAND
```
Run `rive --help` for this list in your terminal, and `rive --version` to print the
installed version.
## Commands
| Command | Does |
| - | - |
| `rive create` | Scaffold a Rive project locally. It creates the following: `rive.yaml`, `scene.rml`, `AGENTS.md`, `.gitignore` |
| `rive ` | Open the preview window and rebuild as you edit. The directory defaults to `.` |
| `rive login` | Sign in with your Rive account. Creates a Free Workspace if you aren't a member of any Workspace. See [`workspace`](#workspace) |
| `rive logout` | Sign out |
| `rive whoami` | Show who you are signed in as |
| `rive docs` | The CLI's own authoring documentation |
| `rive samples` | Clone a runnable example project to your machine |
| `rive schema` | Look up types |
| `rive inspect` | Print the resolved scene |
| `rive build` | Ship the project as an Android or iOS app |
| `rive push` | Build the project and upload it to a Rive file in your account. Needs `rive login` |
| `rive pull` | Overwrite the local project from the Rive file it is linked to. Needs `rive login` |
| `rive ls` | List the projects, folders and files in your Rive account. Needs `rive login` |
| `rive workspace` | Show the current Workspace and your role in each Workspace, switch to another, or create a Free one. Needs `rive login` |
| `rive open` | Open a Rive file in the Editor in your browser. Needs `rive login` |
| `rive library` | Inspect, update and publish Rive libraries. Needs `rive login`, except `library list` |
| `rive doctor` | Check the environment: version, auth, ports, project |
| `rive lsp` | Language server over stdio, for editor integrations |
| `rive update` | Install the latest published CLI |
| `rive switch` | Pick a CLI version, or select one by name |
| `rive uninstall` | Remove a cached CLI version |
| `rive analytics` | Show or set [usage analytics](#usage-analytics) (`on` \| `off`) |
> [!NOTE]
>
> `update`, `switch` and `uninstall` are only supported for the installer build under
> `~/.rive/bin`. If installing the CLI via Homebrew, use the `brew` methods to manage CLI versioning and updates.
## Project flags
These apply to `rive `.
### Build modes
Mutually exclusive, so pick one. `--screenshot`, `--semantics`, `--data-dump` and
`--render-audio` under [Capture](#capture) each count as one of them. With none of them, the CLI opens the preview window and rebuilds as
you edit.
| Flag | Does |
| - | - |
| `--verify` | Check the project without writing a `.riv`. Exit 1 on errors |
| `--publish[=]` | `local` (the default) writes a signed `.riv`. `web` builds, signs and publishes a hosted page. Needs `rive login`. See the note below for publishing without a watermark. Exit 1 on errors |
| `--test` | Run `Tests` scripts. Exit 6 on failures |
> [!NOTE]
>
> `--publish` writes a `.riv` with no watermark when the Workspace the publish counts
> against is on the [Cadet plan or higher](https://rive.app/pricing). Otherwise it adds
> a watermark and names that Workspace. Admins of that Workspace get a link to upgrade,
> and everyone else is told to ask an admin.
>
> A project bound to a file counts against the file's Workspace. Binding is done by
> [`rive push`](/docs/cli/reference/project-config#pushing-to-a-rive-file), which records
> `push.fileId` in `rive.yaml`. Other projects count against the Workspace you choose
> with [`rive workspace`](#workspace), or the only one where you're an Editor. A web
> publish from a project that isn't bound to a file counts against the Workspace that
> owns the page. See
> [Which Workspace counts](/docs/cli/monthly-allowance#which-workspace-counts).
### Modifiers
These attach to whichever mode you chose.
| Flag | Does |
| - | - |
| `--init` | Write `rive.yaml` if missing, then continue |
| `--rev=` | Also write an editor `.rev`. Needs `rive login`. Combines with `--publish[=local]`. On its own it builds without writing a `.riv`, then exits. Refused with `--verify`, `--test` and `--screenshot` |
### Capture
| Flag | Does |
| - | - |
| `--screenshot[=]` | Build, render one frame without a window, write a PNG. Defaults to `build/.png` |
| `--viewport=` | The size the scene is laid out at: the capture size with `--screenshot`, and the window size when watching. Defaults to the artboard's own size |
| `--bench=` | Build, time that many frames without a window, report advance and render statistics plus WASM memory growth |
| `--semantics[=]` | Build, run headless, write the accessibility tree as JSON. Defaults to `build/.semantics.json` |
| `--render-audio[=]` | Build, run headless with no audio device, write what the scripts' audio processors render as a WAV. Defaults to `build/.wav` |
| `--audio-rate=` | The sample rate `--render-audio` renders at. Defaults to `48000` |
| `--audio-channels=` | The channels `--render-audio` renders. Defaults to `2` |
| `--probe=` | Print the capture's color at that point as `AARRGGBB`. Repeatable |
| `--compare=` | Print how many pixels differ from an earlier capture |
| `--scale=` | Shrink the written PNG by this factor, above `0` and at most `1` |
| `--seed=` | The seed scripts' `math.random` starts from. Defaults to `1` |
`--bench` runs instead of `--screenshot`, not alongside it. Passing both times the
frames and writes no PNG, without saying so. It is a build mode in its own right, so
it does not combine with `--verify`, `--publish` or `--test`. It renders at
the artboard's own size and ignores `--viewport`, and it runs 300 warm-up frames
before the ones it times.
### Driving the scene
| Flag | Does |
| - | - |
| `--data=` | Set one view model property. Before any interaction it sets a starting value; after one it applies at that point and runs a frame. Repeatable |
| `--pointer=` | Simulate one pointer event at artboard coordinates. Repeatable |
| `--advance=` | Step the scene forward. Repeatable, and runs in order with the other interactions |
| `--key=` | Simulate a keystroke. Repeatable, and runs in order with the other interactions |
| `--touch=` | Simulate a finger: `down`, `up`, `move` or `tap`, each id its own pointer. `drag@x1,y1>x2,y2+x3,y3>x4,y4` drags fingers together, which is how you pinch. Repeatable |
| `--gamepad=` | Simulate a gamepad event: `connect`, `disconnect`, `button@:down\|up\|<0..1>`, `axis@:<-1..1>`. Repeatable |
| `--semantic-action=` | Fire `tap`, `increase` or `decrease` on the node carrying that accessibility label. Repeatable |
| `--data-dump[=]` | Write the bound view model values, globals and nested artboards as JSON. Defaults to `build/.data.json`; `-` or `stdout` writes to standard output |
| `--data-dump-filter=` | Keep only these property paths, comma separated. Globs allowed, as in `battery/*,score` |
| `--data-dump-every=` | Sample every N frames rather than once at the end, as JSON Lines |
| `--artboard=` | Artboard to show on launch. An unknown name falls back to the first artboard without warning |
| `--fit=` | How the artboard maps into the view: `fill`, `contain`, `cover`, `fit-width`, `fit-height`, `none`, `scale-down`, or `layout` (the default) |
Interactions run in the order you write them, and every one of them needs a capture
mode: `--screenshot`, `--semantics`, `--data-dump` or `--render-audio`.
#### Advancing time
`--advance` steps the scene where it sits among the other interactions. A bare number
is whole frames at 60fps; `1s` or `250ms` is animation time, stepped in 1/60s frames
with one shorter frame for any remainder. The time forms take a decimal point, so
`1.5s` is 90 frames.
```bash theme={null}
rive myproject --screenshot=out.png --advance=60 # 60 frames
rive myproject --screenshot=out.png --advance=1s # the same, written as time
rive myproject --screenshot=out.png --advance=250ms
```
Position it for what you need:
| Where | Does |
| - | - |
| Before a gesture | Plays an intro before the interaction lands |
| Between two gestures | Lets one action's transition finish before the next starts |
| After the last gesture | Settles the scene before the capture |
```bash theme={null}
rive myproject --screenshot=out.png \
--advance=1s \
--pointer=click@120,60 \
--advance=20
```
A sign, whitespace, trailing text, a decimal point on a bare frame count, or a value
above a 32-bit unsigned integer is rejected with exit code 2.
> [!NOTE]
>
> `--advance` replaces `--frame`. A bare `--advance=N` means what `--frame=N` meant, so
> `--frame=20` becomes `--advance=20`. Passing `--frame` is an error naming `--advance`.
>
> `--bench` takes its own frame count and does not combine with `--advance`, `--pointer`,
> `--gamepad`, `--semantics` or `--semantic-action`.
#### Setting data
`--data` takes a property path and a value. The path starts at the view model
instance bound to the artboard, and every segment is a property name, so a flat view
model takes the bare property and a nested one takes a path:
```bash theme={null}
rive myproject --screenshot=out.png --data=level=100
rive myproject --screenshot=out.png --data=battery/level=100
```
A `--data` before any interaction sets a starting value. One placed after a
`--pointer`, `--touch`, `--key`, `--gamepad`, `--semantic-action` or `--advance`
applies at that point in the sequence and then runs a frame, so you can change data
mid-run. Repeat the flag to set several:
```bash theme={null}
rive myproject --screenshot=out.png \
--data=settings/speed=42 \
--data=settings/scale=9
```
> [!NOTE]
>
> A path that matches no property fails the run with
> `--data : no property at this path` and exit 1, and no capture is written. An
> artboard with no view model bound reports
> `--data : no view model is bound to this artboard` instead. Both print even
> under `--quiet`.
#### Reading data back
`--data` sets values going in; `--data-dump` reads them back out. It builds, runs
headless, and writes the bound view model values as JSON, so a test can assert on
what the scene computed:
```bash theme={null}
rive myproject --data-dump=- --advance=60
```
`--data-dump-every` turns that into a time series instead of a single reading: a
header, a frame-0 baseline, then only what changed on each sample, written to
`build/.data.jsonl`. It takes a whole
number of frames at 60fps, and counts the frames gestures advance internally.
#### Simulating a keystroke
`--key` sends a key through the same dispatch path a real one takes. The phase is
`down`, `repeat` or `up`, and defaults to `press`, which is a down then an up.
Modifiers attach with `+`:
```bash theme={null}
rive myproject --screenshot=out.png --key=right
rive myproject --screenshot=out.png --key=a:down
rive myproject --screenshot=out.png --key=tab:down+shift
```
Key names are the same ones the markup uses, so `right`, `escape`, `f1` and `kpEnter`
all resolve.
> [!NOTE]
>
> Keys only reach whatever holds Rive focus. With nothing focused, the CLI says so and
> names the fix: the file needs a `FocusData` on the listener's target, and something to
> focus it.
#### Simulating a pointer
`--pointer` takes a kind and a position. `down`, `up`, `move`, `exit`, and `click` each
take a single point. `click` expands to a move, a press and a release with a frame between
each, because a state machine only sees a gesture when it next runs:
```bash theme={null}
rive myproject --screenshot=out.png --pointer=click@120,60
```
`wheel@x,y:dx,dy[:notches]` and `trackpad@x,y:dx,dy[:steps]` scroll the content by
`dx,dy` in artboard units. A wheel is one notch unless counted, and a trackpad is a
two-finger swipe that flings, defaulting to 8 steps.
`--pointer` only checks the shape of the value. A kind it does not know parses fine,
then fails at delivery with `pointer: unknown gesture` and exits with `1`.
`drag` is a fifth kind, and the only one with a different shape:
`drag@x1,y1>x2,y2[:steps]`. It moves to the first point, presses, emits `steps` moves
along the line to the second point, then releases. `steps` defaults to 8. Every event
gets its own frame, so a drag runs for `steps + 3` frames: a higher count is a finer
and slower sweep, a lower one a flick. Scroll physics reads the velocity that implies,
so the count changes how far a scroll throws.
```bash theme={null}
rive myproject --screenshot=out.png --pointer='drag@200,300>200,80:12'
```
> [!NOTE]
>
> Quote the `drag` value so the shell does not read `>` as a redirection.
### Serving
| Flag | Does |
| - | - |
| `--serve[=port]` | Also push builds to connected players. Defaults to port `9640` |
| `--headless-serve` | Serve with no local window. Takes its port from `--serve=` |
| `--device=` | Serve, and put the player on that device, emulator or simulator |
| `--android`, `--ios` | The same on the first device of that kind |
| `--device-backend=` | How an Android device draws |
### Other
| Flag | Does |
| - | - |
| `--allow-net` | Let scripts `fetch()` `https:` URLs. Without it `fetch` rejects with `disabled` |
| `--output-dir=` | Override `output.dir` for local publishing and for the local row of `--list-published`. Relative to the project, and it does not change `rive.yaml` |
| `--define=` | Set an AnimaScript build constant, `1` by default. Repeatable, and overrides `defines` in `rive.yaml` |
| `--quiet` | No terminal log, compiler errors included. Script `print` output and script errors still print. Read the exit code, `--format=json`, or `logs.problems` instead |
| `--optimize` | Compile Luau at O2 instead of O1, and AnimaScript without its debugger line probes. Both run faster and are harder to debug |
| `--no-status-bar` | Hide the window's [status bar](/docs/cli/reference/status-bar). Paid plans only |
| `--format=json` or `--format=human` | `human` is the default terminal log. `json` needs `--verify`, `--publish[=local]` or `--test`, and prints one JSON report object on stdout. `--json` is an alias for `--format=json` |
## Publishing to the web
`--publish=web` builds, signs and hosts the project as a page anyone can open. See
[Publishing to the web](/docs/cli/publishing).
## Preview window commands
Type these in the terminal while the preview window is open.
| Key | Does |
| - | - |
| `s` or `screenshot [path]` | Write a PNG of the window |
| `p` or `pause` | Toggle playback |
| `a` or `artboard [name]` | Switch the shown artboard |
| `f` or `fit [mode]` | Switch how the artboard maps into the window. Bare `f` lists the modes |
| `z` or `size` | Resize the window to the artboard, and follow it again after a manual drag |
| `d` or `data [path]` | Write the bound data as JSON. `-` or `stdout` writes to standard output |
| `rev [path]` | Write an editor `.rev`. Needs `rive login` |
| `b` or `bar` | Show or hide the [status bar](/docs/cli/reference/status-bar). Paid plans only |
| `?` or `help` | List commands |
## Per-command flags
### `create`
```bash theme={null}
rive create # prompt for a name, then write that directory
rive create # write the project in (`.` is the cwd)
rive create [dir] --from-rev=
```
`--from-rev` converts an editor `.rev` into a project: `scene.rml` plus its scripts
and assets as files. Without a ``, the `.rev`'s own name is used. The directory
must be empty or new.
`--from-remote-file` does the same conversion on a file downloaded from your Rive
account. Without a file ID, the CLI lists your projects and files to pick from. `rive.yaml`
records the link, so `rive push` updates that source file and `rive pull` brings any remote changes in.
This requires a logged in session with `rive login`.
```bash theme={null}
rive create myproject --from-remote-file # pick from a list
rive create myproject --from-remote-file=512 # or name the file id
```
### `schema`
```bash theme={null}
rive schema # properties of a type, inherited included
rive schema --search # find a type or property by name, then pick one
```
| Flag | Does |
| - | - |
| `--list` | Pick a type to describe. Where no picker can draw, prints every type name |
| `--animatable` | Only properties that can be keyed |
| `--bindable` | Only properties that can be data bound |
| `--all` | Include editor-only properties |
| `--json` | JSON output: the type as one object, or the `--list` / `--search` results as an array |
### `docs`
```bash theme={null}
rive docs # the documentation index
rive docs # one topic, for example `layout` or `luau/protocols`
```
| Flag | Does |
| - | - |
| `--list` | Every topic with a description |
| `--pick` | With `--list` or `--search`, pick one to read |
| `--search ` | Lines matching text across every topic |
| `--path` | Print the docs directory on disk |
### `samples`
```bash theme={null}
rive samples # pick one and copy it into a new directory
rive samples --path # print the samples directory on disk
```
### `inspect`
```bash theme={null}
rive inspect [dir] # resolved scene as JSON. The directory defaults to `.`
```
Exits `1` when `problems` contains an error, and `1` with a message on stderr when
the directory has no `rive.yaml`.
| Flag | Does |
| - | - |
| `--json` | JSON output (the default) |
| `--summary` | Problems, object counts per type and per artboard, counts for the other roots such as view models and enums, and each event with what fires it. Not the tree |
| `--all` | Include editor-only properties |
| `--artboard=` | One artboard only. An unknown name gives an empty `artboards` list and still exits `0` |
### `push`
```bash theme={null}
rive push [dir] # build the project and send it to the bound Rive file
```
This uploads the project to your Rive account, replacing the bound file's contents and adding an
entry to its revision history. It is the same artifact `--rev` would export.
| Flag | Does |
| - | - |
| `--project=` | Project for the first push or `--new-file`. Falls back to `push.projectId` in `rive.yaml` |
| `--folder=` | Folder for the first push or `--new-file` |
| `--new-file` | Create a new file and link the project to it, even when `rive.yaml` already links one |
| `--yes` | Skip the confirmation. A push to an already-linked file asks first, so this is required in CI |
| `--define=` | Set an AnimaScript build constant. Repeatable |
| `--name=` | Revision history label. Defaults to `rive-cli push` |
| `--optimize` | Compile scripts at O2 |
| `--quiet` | Suppress build logs |
See [Pushing to a Rive file](/docs/cli/reference/project-config#pushing-to-a-rive-file).
### `pull`
```bash theme={null}
rive pull [dir] # overwrite the project from its linked Rive file
```
Downloads the Rive file the project is linked to and writes it over the project: the
scene markup, and every script, shader and asset as a file. Files whose bytes already
match are left alone, and build inputs missing from the remote file are reported
rather than deleted.
`rive.yaml` takes the remote file's main artboard and build settings and keeps every
other line. `AGENTS.md`, `CLAUDE.md` and anything else you added are untouched.
| Flag | Does |
| - | - |
| `--yes` | Skip the confirmation. Required in CI, and anywhere there is no terminal to ask on |
| `--quiet` | Only report what changed |
This command names the file and the project and asks before it runs, defaulting to no:
```text theme={null}
Pulling file 2603061 overwrites /path/to/myproject's scene, scripts and assets with the remote file's.
Overwrite local changes? [y/N]:
```
> [!WARNING]
>
> At this time, pull replaces your local project's scene, scripts and assets with the remote file's.
### `ls`
```bash theme={null}
rive ls # projects in the current Workspace
rive ls # folders and root files
rive ls # one folder
rive ls --all # every file in the project, with its folder path
```
Lists what is in your Rive account, one Workspace at a time. It only reads.
| Flag | Does |
| - | - |
| `--all` | With a project id, every file in the project with its folder path |
| `--plain` | Print the table instead of browsing |
| `--json` | One JSON object per line, rows only |
| `--workspace=` | List another Workspace, for this run only |
On a terminal it browses: arrows move, enter or right opens, left or backspace goes
up, typing filters, escape quits. Piped, under an agent, or with `RIVE_NO_TUI=1`, it
prints instead. Every row names its kind and its id, and the JSON keys are
`projectId`, `folderId` and `fileId`, which are the ids the other commands take:
```bash theme={null}
rive ls 1708481 --json # find a file id
rive open 2564593 # open it in the Editor
```
### `workspace`
```bash theme={null}
rive workspace # the current Workspace, and your role in every one you can switch to
rive workspace # switch to that Workspace
rive workspace create # create a Free Workspace and switch to it
```
`rive ls` and `rive push` work one Workspace at a time, and this chooses which. Until
you switch, the current Workspace is the only one where you're an Editor. If you're an
Editor in several or in none, no Workspace is current until you choose one: in a
terminal, `rive ls` without a project id and a first `rive push` open a picker, and
anywhere else they list your Workspaces and exit with code `10`. The choice persists. Use
`rive ls --workspace=` to read another one without switching.
The list shows your role in each Workspace, Editor or Viewer. `rive workspace ` takes
an id from that list.
A publish from a project that isn't bound to a file counts against the current
Workspace, and needs you to be an Editor in it. If you haven't chosen a Workspace and
you're an Editor in several, the CLI stops the publish and exits with code `10`. A web
publish doesn't need this choice: it counts against the Workspace that owns the page,
whichever Workspace you choose here. See
[Which Workspace counts](/docs/cli/monthly-allowance#which-workspace-counts).
`rive workspace create ` creates a Workspace on the Free plan, with you as its
admin, and makes it the current Workspace. The name is 3 to 60 characters. Put quotes
around a name with spaces. The CLI prints
`created a Free Workspace: (), now the current one`.
If you aren't a member of any Workspace, the CLI creates a Free Workspace for you,
right after `rive login` signs you in, or when you next run a command that needs a
Workspace. In a terminal, it asks you for a name and suggests your name followed by
`'s Workspace`. Without a terminal, as when an agent runs the CLI, it uses that
suggestion. It prints `created a Free Workspace: ()`. The new Workspace is
the only one where you're an Editor, so it's the current one: `rive ls` and
`rive push` use it, and publishes from projects that aren't bound to a file count
against it.
| Flag | Does |
| - | - |
| `--json` | One JSON object per Workspace, rows only |
| `--format=json` | With `create`, print the new Workspace as one JSON object with its `id` and `name` |
### `open`
```bash theme={null}
rive open # open the file in the Editor, and print its url
rive open --print # print the url, open no browser
```
Works for any file you can open, and `rive ls` prints file ids.
| Flag | Does |
| - | - |
| `--print` | Print the url without opening a browser |
### `library`
```bash theme={null}
rive library list [dir] # what this project imports
rive library search [dir] # what it may import
rive library info [dir] --library= # one library's versions
rive library update [dir] # move imports to the newest version
rive library publish [dir] # publish this project's file as a library
```
A library is content published in Rive that other files import: artboards marked as
components, view models, enums, scripts and shaders. What a project imports is
recorded in the `libraries` block of
[rive.yaml](/docs/cli/reference/project-config), and `rive pull` downloads the snapshots.
`library list` reads the project's own markup, so it runs offline and needs no
session. The rest need `rive login`.
> [!NOTE]
>
> `library search` and `library publish` depend on the Workspace's plan. Where it is not
> enabled the CLI says so and names the account page to upgrade on. `library list`,
> `library info` and `library update` have no such check.
Each subcommand takes its own flags.
| `library list` | Does |
| - | - |
| `--json` | One JSON object per reference, rows only |
| `library search` | Does |
| - | - |
| `--match=` | Only libraries whose name contains the text |
| `--project=` | The Rive project to answer for, instead of the one this project is linked to. Lets this run outside a project |
| `--json` | One JSON object per library, rows only |
| `library info` | Does |
| - | - |
| `--library=` | Which library, by its library id. Required. `library list` and `library search` both print it |
| `--version=` | Only that version, instead of all of them |
| `--json` | The library as one object, versions nested |
| `library update` | Does |
| - | - |
| `--library=` | Only that library. Omit for every one with a newer version |
| `--yes` | Skip the confirmation. Required where there is no terminal to ask on |
| `library publish` | Does |
| - | - |
| `--description=` | Note shown against this version |
| `--yes` | Skip the confirmation |
A library is named by its id rather than its name, because a library's name is its
source file's name and can change at any time. `library search` takes `--project` to
answer for a project other than this one; `library info` does not, since an id names
a library on its own.
> [!WARNING]
>
> `library publish` pushes the project before publishing, because a version is cut from
> the file's content. That push overwrites the remote file, so run `rive pull` first if
> someone else has been working in it.
### `doctor`
```bash theme={null}
rive doctor [project-dir]
```
| Flag | Does |
| - | - |
| `--format=json` | Machine-readable report on stdout |
`doctor` prints a row per check, each `ok`, `warn` or `fail`. `version`, `update`,
`auth`, `live-link` and `project` cover authoring, and further rows report on device
builds where the platform supports them. It exits `0` when everything is `ok` or
`warn`, and `1` when a check fails.
## Signing in
| What you run | Session needed |
| - | - |
| `--publish`, `--rev`, `rive push`, `rive pull`, `create --from-remote-file`, `rive ls`, `rive workspace`, `rive open`, `library` except `list` | Yes, with `rive login` |
| Preview window, `--verify`, `--test`, `--screenshot`, `--serve`, `--headless-serve` | No, and these work offline |
| `create`, `docs`, `samples`, `schema`, `inspect`, `library list` | No |
| `update`, `whoami`, `doctor` | No account, but they reach the network. `whoami` exits `3` when you are not signed in and `7` when it cannot reach Rive; `doctor` reports a missing session as a warning and still exits `0`, but exits `1` when a check fails |
Credentials live outside the project: `~/.config/rive/app.rive.cli/` on macOS and
Linux, honouring `XDG_CONFIG_HOME`, and Windows Credential Manager on Windows.
> [!NOTE]
>
> A gated mode checks the session live, so `--publish` and `--rev` fail on a dropped
> connection even with valid stored credentials.
## Exit codes
| Code | Meaning |
| - | - |
| `0` | OK |
| `1` | Build errors, or any failure without a more specific code |
| `2` | An unknown flag, or one the CLI parsed and rejected: a bad `--pointer`, `--data`, `--advance` or `--viewport` value; `--frame` or `--once`, which are gone; `--format` given anything but `json` or `human`; `--format=json` without a build mode; two build modes at once; `--rev` with a mode that writes nothing; an interaction with no `--screenshot`; or `rive` with no arguments outside a project |
| `3` | Not logged in, or the session was rejected |
| `6` | Test cases failed. The build itself was fine |
| `7` | A service could not be reached, so it is safe to retry |
| `8` | This CLI is below the published minimum. Run `rive update` |
| `9` | The Workspace used its [monthly CLI allowance](/docs/cli/monthly-allowance). Retrying does not help until it resets or the Workspace upgrades |
| `10` | You haven't chosen a Workspace, and the CLI can't pick one for you. A publish from a project that isn't bound to a file stops here when you're an Editor in several. `rive ls` without a project id, and a first `rive push`, stop here when they can't open a picker and you're an Editor in several or in none. Choose one with `rive workspace `, using an id the CLI lists. A web publish doesn't need this choice, because it uses the page's Workspace. See [Which Workspace counts](/docs/cli/monthly-allowance#which-workspace-counts) |
> [!NOTE]
>
> Any argument without a leading `--` is read as the project directory. Passing more
> than one is not an error: the CLI builds the one furthest right and says nothing about
> the others, so a stray word changes what gets built.
## JSON output
`--format=json` on `--verify`, `--publish[=local]` or `--test` prints one JSON
object on stdout. `data` differs per mode. `--verify` and `--publish` carry the build:
```json theme={null}
{"success": true, "command": "publish", "data": {"riv": "./build/myproject.riv", "bytes": 140, "buildMs": 2.0, "problems": []}, "errors": [], "warnings": []}
```
`--test` carries the run:
```json theme={null}
{"success": false, "command": "test", "data": {"passed": 5, "failed": 1, "noTestsFound": false, "failures": [{"test": "clamp > intentional failure", "line": 29, "message": "5 is not equal to 10"}]}, "errors": ["clamp > intentional failure: 5 is not equal to 10"], "warnings": []}
```
`command` names the mode: `"verify"` for `--verify`, `"publish"` for `--publish`,
`"test"` for `--test`. Each entry in
`data.problems` is `{severity, kind, code, script, line, column, message}`, with
`severity` one of `error`, `warning` or `hint`. `errors` repeats them as
`script:line message` strings. `data.riv` is `null` on `--verify`
and on any failed build. Logs stay on stderr, so stdout carries nothing else.
Each of these reports also has an `allowance` field and a `workspace` field.
`allowance` is `null` unless the [monthly CLI allowance](/docs/cli/monthly-allowance)
stopped the run, which only `--publish` can do. `workspace` names the Workspace a
`--publish` run counts against. It's `null` on the other modes, and when Rive doesn't
name one. See [Which Workspace counts](/docs/cli/monthly-allowance#which-workspace-counts).
## Environment variables
| Variable | Overrides |
| - | - |
| `RIVE_API_BASE` | The API host. A custom host also gets its own stored login |
| `RIVE_NO_TUI` | Any value except `0` disables interactive pickers |
| `TERM` | Unset, empty, or `dumb` disables interactive pickers |
| `NO_COLOR` | Draws pickers without color |
| `RIVE_HOME` | The CLI's install and state root. Defaults to `~/.rive` |
| `XDG_CONFIG_HOME` | Relocates the credential directory on macOS and Linux |
| `RIVE_DOCS_DIR` | The directory `rive docs` reads |
| `RIVE_SAMPLES_DIR` | The directory `rive samples` copies from |
| `RIVE_ANALYTICS` | Turns usage analytics on or off: `on`/`1`/`true`/`yes`, or `off`/`0`/`false`/`no`. Wins over `DO_NOT_TRACK`, `CI` and `rive analytics` |
| `DO_NOT_TRACK` | Any non-empty value except `0` or `false` turns usage analytics off |
| `CI` | Any non-empty value except `0` or `false` keeps usage analytics off while no setting is stored, as on a fresh CI machine |
| `AI_AGENT` | Tells the CLI that a coding agent is running it, for agents the CLI doesn't recognize itself. The CLI then skips questions and pickers, usage analytics name the agent, and `rive push` stores the agent's name with the edits it uploads. The name is the value in lowercase when it starts with a letter or digit and has up to 32 letters, digits, `.`, `_` or `-`. A version at the end, such as `@2.0`, is dropped. Any other value gives the name `other`, and so do `1`, `true`, `yes` and `on`. `0`, `false`, `no` and `off` mean no agent |
> [!NOTE]
>
> Interactive pickers draw on stderr, so redirecting stdout alone does not disable
> them. Where no picker can draw (`TERM=dumb`, `RIVE_NO_TUI=1`, or stdin not a
> terminal as in CI), the CLI falls back to printing the list instead.
## Usage analytics
The CLI sends usage analytics to help improve Rive. Each run reports:
* The command name, never argument values, file names or file content
* The CLI version, operating system and language
* A random ID for this install
* Whether the command ran in a terminal or was started by a coding agent
* The coding agent's name, such as `codex`. When the CLI doesn't recognize the agent, the name comes from [`AI_AGENT`](#environment-variables)
* Your Rive account ID and plan, when you're signed in
The preview window also reports when its status bar shows an upgrade button, and which status bar items you click. Events carry no IP address or location.
The first run prints a notice and sends nothing. Analytics start with the next run. The CLI saves events under `~/.rive` and a background process sends them, so a command never waits on the network.
To turn analytics off, run `rive analytics off`, or set `RIVE_ANALYTICS=off` or `DO_NOT_TRACK=1`. Run `rive analytics` to see the current setting, and the variable that set it, if any.
# Project Configuration
Source: https://rive.app/docs/cli/reference/project-config
Project layout and rive.yaml keys.
A project is any directory containing a `rive.yaml`. Only `name` is required:
```yaml rive.yaml theme={null}
name: myproject
```
## File discovery
Everything else in the directory is bundled by extension. There is no manifest to
maintain.
| Extension | Becomes |
| - | - |
| `.luau` | Scripts, both protocol scripts and importable modules |
| `.as` | AnimaScript (new). Requires `scripting: wasm` |
| `.wgsl` | Shaders, compiled to RSTB |
| `.rml` | The scene. A project can hold any number of markup files, in any folders, and they compile as one document |
| `.png` `.jpg` `.jpeg` `.webp` | Image assets |
| `.ttf` `.otf` | Font assets |
| Anything else | A blob asset, findable by name from scripts |
> [!NOTE]
>
> This is how sources are *discovered*, not a promise that everything in the directory
> ends up in the `.riv`. Assets embed when something references them, either a `file=`
> in the RML or a lookup by name from a script. A font or image nothing uses adds nothing to
> the output.
>
> Scripts and shaders are the exception: every `.luau` and `.wgsl` in the scan is
> compiled into the file whether or not anything references it. Use `exclude` to keep
> one out.
Markup files compile together, so an id declared in one file can be referenced from
another. Ids may not repeat across files, and a problem is reported against the file
it is in. Split by whatever reads well, such as artboards in one file and view models
in another.
Dot-files and dot-directories are skipped, and so are `rive.yaml`, whatever
`output.dir` points at, anything ending `.riv`, `.rev` or `.log`, and editor backups
ending `~`. A log file that does not end `.log` and sits outside `output.dir` is
bundled like any other file.
Asset paths in RML are project-relative:
```xml theme={null}
```
A conventional project on disk:
```text theme={null}
myproject/
rive.yaml
scene.rml
main.luau
mathutil.luau
Montserrat.ttf
logo.png
build/
```
## Full shape
```yaml rive.yaml theme={null}
name: myproject
main: main
scripting: bytecode # or "wasm", required for .as files
debugLevel: none # none | medium | max
optimizationLevel: max # none | medium | max
artboard:
width: 800
height: 600
background: "#1D1D1D" # quote it, a bare # starts a YAML comment
artboards:
main:
width: 1920
height: 1080
exclude:
- docs
excludeFromRev:
scripts:
- "*_test"
artboards:
- tests/*
assets:
- raw_*
contents:
- logo
libraries: # written by the tool
"palette":
fileId: 4002
libraryId: 42
version: 1
override: ../palette # optional, and the only part you write
pages: # written by the first --publish=web
workspaceId: 77
name: "my-scene"
revFlavor: editable # or "library"
window:
statusBar: false # paid plans only
output:
dir: build
logs:
file: build/rive.log
problems: build/problems.log
```
## Keys
**`name`** — Required. Also the name other projects use to import this one.
**`main`** — Which artboard is the file's default, by name. A name that matches no
artboard fails the build. Without the key, the first artboard declared wins, and
markup files compile in path order, so that depends on filenames sorting the way you
expect. Name the artboard here instead.
**`debugLevel`**, **`optimizationLevel`** — The Editor's publish levels for scripts:
`none`, `medium` or `max`. They default to `none` and `max`. A number is not accepted.
**`shaderOutputs`** — The shader backends compiled on publish, a list drawn from
`msl`, `glsl`, `wgsl`, `hlsl` and `spirv`. Defaults to all of them.
**`scripting`** — `bytecode` (the default) or `wasm`. `wasm` is required for `.as`
AnimaScript files.
These and `main` are what the Editor keeps on the file's `Backboard`. A fragment
declares no `Backboard`, so they live here instead and the build synthesizes one from
them.
`create --from-rev`, `create --from-remote-file` and every `rive pull` write the
remote file's `Backboard` into these keys. A setting back at its default has its key
removed rather than left behind, so a hand-set value here does not survive a pull.
**`artboard`** — Default size and background for generated artboards, used only when
there is no `.rml`. Sizes default to 800 x 800. `background` takes `#RRGGBB` or
`#AARRGGBB`; the `#` is required, which is why the value must be quoted. A value the
CLI cannot read is dropped without a warning, leaving the default `#FF1D1D1D`.
**`artboards`** — The same settings as `artboard`, set per artboard. Key each entry by
its layout script's path with `.luau` dropped, so `ui/panel.luau` is `ui/panel`.
**`window.statusBar`** — `false` hides the preview window's
[status bar](/docs/cli/reference/status-bar) on a paid plan. Free and signed-out accounts
always see it.
**`exclude`** — Paths not to bundle at all. An entry matches a file or directory by
exact path, matches everything under a directory, and matches files by glob with the
same `*` and `?` as `excludeFromRev`. `output.dir` is excluded for you. Use it to keep
the scan tidy.
**`excludeFromRev`** — Drops matching things from the exported `.rev` only. The `.riv`
and the preview window always contain everything. Four categories:
| Category | Matches by |
| - | - |
| `scripts` | Module path, for Luau and WGSL |
| `artboards` | Name |
| `assets` | Name |
| `contents` | Asset bytes, keeping the asset referenced but unembedded |
Patterns support `*` (any run of characters, including `/`) and `?` (one character).
Excluding a layout script also drops its generated artboard.
**`libraries`** — The libraries published in Rive that this project's scene imports
directly. The tool writes this block: `rive create --from-remote-file` creates it, and both
`rive pull` and `rive library update` rewrite it, so do not hand-edit `fileId`,
`libraryId` or `version`.
The key is the library's name, lowercased, and it is also the label a `require` writes
after `lib:`:
```lua theme={null}
local ink = require('lib:palette/ink')
```
`override` is yours, and a pull leaves it alone. It points the build at a local
project instead of the downloaded snapshot, so a library and a file that imports it
can be edited together without publishing between every change.
See [`library`](/docs/cli/reference/commands#library) for inspecting, updating and
publishing libraries.
**`revFlavor`** — `editable` (the default) or `library`. `library` exports scripts as
immutable source only, with no editable line tree, which is the flavor published
libraries use. It does not register the file as a library; `rive library publish`
does that.
**`push`** — `projectId` and `fileId`, the link to the Rive file. `rive push` writes it
after the first push, and `rive create --from-remote-file` records it up front.
With `push.fileId` set, a publish counts against the Workspace that owns the file, and
that Workspace's plan decides the allowance and the watermark. Without it, a publish
counts against the Workspace you choose with [`rive workspace`](/docs/cli/reference/commands#workspace),
or the only one where you're an Editor. A web publish from a project without
`push.fileId` counts against the Workspace that owns the page.
See [Pushing to a Rive file](#pushing-to-a-rive-file) and
[Which Workspace counts](/docs/cli/monthly-allowance#which-workspace-counts).
**`pages`** — The hosted page `--publish=web` replaces. `workspaceId` is the ID of the
Workspace that owns the page and `name` is the slug it answers to. The first publish
writes it and later ones leave it alone. `teamId`, the older name for `workspaceId`,
still works. See [Publishing to the web](/docs/cli/reference/commands#publishing-to-the-web).
**`output.dir`** — Where the `.riv` is written. Defaults to `build`.
**`logs.file`** — Append-only interleave of compiler problems, script `print` output
and system messages.
**`logs.problems`** — Rewritten on every build, opening with a
`# rive generation N | E errors, W warnings | OK|FAILED` header, so it always
describes exactly one build. This is the file to read when scripting around the CLI.
Neither `logs` key has a default. Omit them and no log file is written. `rive create`
writes both into the scaffolded `rive.yaml`, pointed at `build/`; a hand-written
`rive.yaml` holding only `name` gets no logs.
Keys the CLI does not know are ignored without a warning, and so is an `artboards:`
entry naming a script that does not exist. A misspelled key will not fail the build.
## Pushing to a Rive file
`rive push` builds the project and uploads it to a Rive file in your account. The file opens from the Editor's file browser
like any other, and every push replaces its contents and adds a named entry to its
revision history, so any push can be inspected or restored from the Editor.
When a coding agent runs the push, Rive stores [the agent's name](/docs/cli/reference/commands#environment-variables) with the edits.
```bash theme={null}
rive login # once per machine, the same session as --publish
rive push # build and push. The first push creates the file
rive pull # bring the remote file's changes back into the local project
```
`rive pull` is the other direction: it overwrites the project from the linked file.
See [`pull`](/docs/cli/reference/commands#pull) for what it replaces and what it leaves
alone.
### The first push
In your Rive account, files are grouped into projects. That is a different thing from
the project folder on your machine: the first `rive push` asks which Rive project to
create the file in, then records your answer so later pushes go back to the same file.
If your account has one project, it is chosen for you. If it has several, the CLI
lists them and you choose. Your Personal Files project appears first in that list,
so a push can land in your own drafts rather than a shared project. Projects you can
only view are left out.
`--project=` and `--folder=` skip the question, and `rive ls` prints your
projects and their ids without building anything.
The file it creates is recorded in `rive.yaml`:
```yaml theme={null}
push:
projectId: 9
fileId: 512
```
If you're working in version control, commit this so everyone pushing the project updates the same file. Delete the `fileId`
line to make the next push create a fresh file, or edit `projectId` to create it
somewhere else.
### Every push after
A later push sends only what differs from the file's live content, then names a
revision:
```bash theme={null}
rive push --name="before the terrain rewrite"
```
A push to an already-linked file asks for confirmation first, so pass `--yes` in CI.
A push with nothing new reports `already up to date` and adds no revision. Previous
content is never lost: it stays in the revision history, and the Editor can restore
any entry.
> [!WARNING]
>
> The push is authoritative. If someone has the file open in the Editor while you push,
> they see the content swap live, and any Editor-made changes to pushed content are
> overwritten.
What gets pushed is exactly what `--rev` would export: the project's own scripts,
assets and artboards, minus everything `excludeFromRev` drops. Libraries are not
pushed, since each one exports its own `.rev` and is published separately.
> [!NOTE]
>
> Push uses the same `rive login` session as `--publish`. If you have any issues, run
> `rive login` to get a new OAuth session going.
# Status Bar
Source: https://rive.app/docs/cli/reference/status-bar
What each stat in the preview window's status bar measures.
The preview window (`rive `) shows a status bar along its bottom edge, on by
default. It is a 28 point strip below the scene. The scene is laid out above it, so
the bar never covers content, and the window grows by the strip so the artboard keeps
its size.
Stats refresh twice a second, each averaged over that half second. Click a stat's
label in the bar to open its section on this page.
> [!NOTE]
>
> The bar is only drawn in the live window. It never appears in screenshots, `--bench`,
> or any other headless run.
## FPS
Frames presented per second in the window. It is capped by the display's refresh
rate: 60 on most displays, and up to 120 on ProMotion displays.
## FRAME
The average time between frames, in milliseconds. A 60 Hz display that is keeping up
shows 16.7 ms. A FRAME well above the display's interval means frames are being
dropped.
## ADVANCE
CPU time to advance the scene each frame. That covers state machines, animations,
layout, data binding, and the `advance` and `update` calls of scripts. In scripted
content, this is the usual cause of jank.
While playback is paused, ADVANCE shows a dash and the bar shows PAUSED. Toggle
playback with [`p`](/docs/cli/reference/commands#preview-window-commands) in the terminal.
## RECORD
CPU time to record the frame's draw commands. Rendering is deferred: the main thread
records the commands and a render thread replays them to the GPU. RECORD covers only
the recording, so it excludes GPU time and presentation.
## HEAP
Memory owned by the file's scripts. A file runs on one script VM, so HEAP reports
whichever one it uses:
| VM | HEAP is |
| - | - |
| AnimaScript | The size of the module's wasm linear memory. It only grows and never shrinks, so it is a high-water mark rather than live allocations |
| Luau | The garbage collector's heap |
A dash means the file has no scripts.
HEAP turns amber when the runtime warns about a script heap growing steadily, which
usually means a leak or an unbounded cache, or about leaked handles. The terminal log
has the details.
## MEM
The whole process's memory, as the operating system counts it:
| Platform | MEM is |
| - | - |
| macOS | The physical footprint, the same number as Activity Monitor's **Memory** column |
| Linux | Resident memory |
| Windows | Private bytes |
MEM includes HEAP, plus the runtime, artboards, images, fonts and GPU driver
allocations, and the CLI's own compiler and file watcher. That makes it much larger
than what the same file uses inside an app. Use it to spot growth over time, not as
an absolute budget.
## VM
The script VM and the tier it runs on:
| Shows | Means |
| - | - |
| AOT | Compiled ahead of time, optimized |
| AOT -O0 | Compiled ahead of time without optimization |
| INTERP | The WebAssembly interpreter, many times slower than AOT |
| LUAU | The Luau VM |
A dash means the file has no scripts.
> [!NOTE]
>
> Script timings in the live window are slower than in a published file, because the
> live window's development builds meter every loop for the watchdog. To time scripts,
> use `rive --bench=N`, which uses release builds.
## Account and plan
The right side of the bar shows your account:
| You are | The bar shows |
| - | - |
| Signed in | @USERNAME, linking to your account page |
| Signed in on a free plan | @USERNAME, FREE PLAN and an **UPGRADE** button |
| Signed out | NOT SIGNED IN and **UPGRADE** |
### Hiding the bar
On a paid plan, you can hide the bar in any of these ways:
| Where | How |
| - | - |
| The terminal, while the window is open | Type `b` |
| The command line | Pass `--no-status-bar` |
| `rive.yaml` | Set `window.statusBar: false` |
```yaml rive.yaml theme={null}
window:
statusBar: false
```
Free and signed-out accounts always see the bar.
# Community
Source: https://rive.app/docs/community/community-overview
# Marketplace
Source: https://rive.app/docs/community/marketplace
# Marketplace Overview
Source: https://rive.app/docs/community/marketplace-overview
The [Rive Marketplace](https://rive.app/marketplace?utm_source=docs\&utm_medium=content) is a place where creators can share their files, get feedback, and learn by opening others’ files directly in the Rive editor.
Marketplace files are all shared under a [CC BY](https://creativecommons.org/licenses/by/4.0/) license.
## Marketplace examples in the editor
The **Home** view of the [File Browser](/docs/editor/interface-overview/file-browser#home) includes a **Marketplace Examples** section with files you can open and learn from. Click **View all** to open the Marketplace in your browser.
## Remixing
A Remix is a copy of another user's file. It uses their file as a starting point for a new file in your account. Remixing encourages sharing, and you'll probably learn some new techniques too!
To Remix a file from the Marketplace, find one you like, click on the thumbnail, and use the remix button on the right side.

The file will open in the editor, and a new copy is added to your file browser.
# Rive Experts
Source: https://rive.app/docs/community/rive-experts
# Support
Source: https://rive.app/docs/community/support
Choose the best way to get help with Rive—from community support to direct help from our team.
## Quick links
Not sure where to start? Ask in the [community](https://community.rive.app/c/support?utm_source=docs\&utm_medium=support_page\&utm_content=peer_support) — you’ll usually get the fastest response.
### Get help
* [Peer-to-peer Support](https://community.rive.app/c/support?utm_source=docs\&utm_medium=support_page\&utm_content=peer_support) — Best for how-to questions, learning Rive, and general debugging help from the community
* [Voyager Support](https://community.rive.app/c/voyager-support?utm_source=docs\&utm_medium=support_page\&utm_content=voyager_support) — Priority support with direct help from the Rive team for production issues and blocking bugs (included with Voyager)
* [Enterprise](https://rive.app/pricing?utm_source=docs\&utm_medium=support_page\&utm_content=enterprise_support) - For teams that need closer collaboration, Enterprise plans include a dedicated Slack channel with the Rive team
* [Discord](https://discord.gg/rive-app) — Chat with the community in real time for quick questions and discussion
* [Account support](https://forms.rive.app/support?utm_medium=support_page) — Billing, account issues, or private inquiries
> [!TIP]
>
> For faster, more accurate help, include a `.rev` file, a video, a code snippet, and a minimal example.
### Report & request
* [Report a Bug](https://community.rive.app/c/bug-reports?utm_source=docs\&utm_medium=support_page\&utm_content=bug_report) — Report issues with the editor or runtimes
* [Request a Feature](https://community.rive.app/c/feature-requests?utm_source=docs\&utm_medium=support_page) — Suggest improvements or new features
* [Early Access](https://community.rive.app/c/early-access?utm_source=docs\&utm_medium=support_page) — Discuss and give feedback on early features
***
## FAQs
> [accordion] Do you offer student discounts?
>
> Yes. See [Rive Student Plan Request](https://forms.rive.app/education?utm_medium=support_page) for details.
> [accordion] Where should I ask technical questions?
>
> For most technical questions, the fastest way to get help is through the community.
> You’ll often get answers from both the Rive team and other experienced users.
>
> If you're working on something production-critical or need direct help from the Rive team, consider [Voyager support](https://rive.app/pricing).
> [accordion] When should I email support?
>
> Use email support for:
>
> * Billing or account issues
> * Security concerns
> * Private or sensitive information
>
> For general how-to questions or debugging help, the community is a better place to start.
> [accordion] What’s included in Voyager support?
>
> Voyager support gives you direct access to the Rive team with faster, more in-depth help.
>
> This is best for:
>
> * Production issues
> * Blocking bugs
> * Help debugging complex setups
>
> [Upgrade to Voyager](https://rive.app/pricing?utm_source=docs\&utm_medium=support_page).
> [accordion] How do I cancel my Rive plan?
>
> See [Cancelling My Plan](/docs/account-admin/account-overview/cancel-my-account).
> [accordion] Where can I find runtime-specific FAQs?
>
> You can browse runtime-specific FAQ pages here:
>
> * [Apple Runtime FAQ](/docs/runtimes/apple/faq)
> * [Flutter Runtime FAQ](/docs/runtimes/flutter/faq)
> * [Web Runtime FAQ](/docs/runtimes/web/faq)
> * [Choose a Renderer FAQ](/docs/runtimes/choose-a-renderer/faq)
# Focus
Source: https://rive.app/docs/editor/accessibility/focus
Let users move through your file with a keyboard or gamepad, and control which element receives their input.
> [!NOTE]
>
> Focus requires a runtime that supports it. See [Focus Feature Support](/docs/feature-support#focus).
Focus determines which element receives keyboard, text, and gamepad input. Only one element has primary focus at a time, but its focusable ancestors are also considered focused. For example, when a button inside a focusable menu has primary focus, the menu has focus too.
Users move focus by clicking an element, pressing **Tab** and **Shift+Tab**, or using the arrow keys, and your state machine can move focus with listener actions.
Focus is what makes your file usable without a pointer. Keyboard users, switch users, and gamepad players all rely on a predictable focus order to reach buttons, inputs, and other interactive elements.
## Making an element focusable
Any element in the hierarchy can receive focus once you add a focus node to it.
**Step 1**
Select the element you want to make focusable.
**Step 2**
In the Inspector, click **+** in the **Focus** section.
**Step 3**
Configure the [focus properties](#focus-properties).
> [!TIP]
>
> [Text inputs](/docs/editor/state-machine/listeners#text-input) and other elements need focus before they can receive typed text or key presses. If a **Keyboard** or **Text Input** listener isn't firing, check that its target has a focus node.
### Focus properties
| Property | Description |
| - | - |
| **Focusable** | Turns focus on or off for the element. When off, the element can't receive focus at all. |
| **Traversable** | Includes the element in **Tab**, **Shift+Tab**, and arrow-key navigation. When off, the element can still receive focus from a click or a **Focus** action, but users can't tab to it. |
| **Behavior** | Controls what happens when focus reaches the first or last element inside this one. See [Focus scopes](#focus-scopes). |
**Focusable** and **Traversable** can be keyed on the timeline and data bound, so you can turn focus on or off as your file changes state. For example, turn off **Focusable** on buttons behind a modal while the modal is open.
## Focus order
**Tab** moves focus to the next traversable element and **Shift+Tab** moves it to the previous one. The order follows the [hierarchy](/docs/editor/interface-overview/hierarchy), from top to bottom. To change the order, reorder the elements in the hierarchy.
The arrow keys move focus directionally, to the nearest focusable element in that direction on the canvas.
An element can't hold focus while it's hidden. If the focused element is collapsed, hidden, or has an opacity of 0, focus moves to the nearest focusable ancestor.
## Focus scopes
When an element with a focus node contains other focusable elements, it acts as a scope: its children form a group in the focus order. The scope's **Behavior** decides what happens when focus reaches the edge of the group.
| Behavior | Description |
| - | - |
| **Parent Scope** | Focus leaves the group and continues to the next element outside it. This is the default. |
| **Closed Loop** | Focus wraps from the last element back to the first, and from the first back to the last. Focus can't leave the group by tabbing. |
| **Stop** | Focus stays on the first or last element. |
Tip
**Example - Trapping focus in a dialog**
When a dialog is open, keyboard users shouldn't be able to tab to the content behind it. Add a focus node to the dialog's group and set **Behavior** to **Closed Loop**. Tabbing now cycles through the dialog's buttons until the dialog closes.
## Reacting to focus
Use the [State Machine](/docs/editor/state-machine/state-machine) to show focus and respond to it.
* **Focus** and **Blur** [listeners](/docs/editor/state-machine/listeners#focus) fire when an element gains or loses focus. Because ancestors share focus, a **Focus** listener on a container fires when focus first enters it, and its **Blur** listener fires when focus leaves it. Moving focus between children inside the container doesn't fire either listener on the container. Use them to show a focus ring, highlight, or other visible focus indicator.
* A **Focus** [transition condition](/docs/editor/state-machine/transitions) checks whether a specific element currently has focus. The condition is true when the element or any of its focusable descendants has primary focus.
* **Keyboard** and **Text Input** listeners respond to input on the element with primary focus. If that element doesn't handle a key, the key passes up to its nearest focusable ancestor.
> [!WARNING]
>
> Always give focused elements a visible focus indicator. Without one, keyboard users can't tell where they are.
## Moving focus with listener actions
Add a **Focus** action to a listener to move focus from your state machine. Choose a mode from the dropdown:
| Mode | Description |
| - | - |
| **target** | Moves focus to a specific element. The target must have a focus node. |
| **traverse** | Moves focus in a direction: **next**, **previous**, **up**, **down**, **left**, or **right**. |
| **clear** | Removes focus from the current element. |
For example, use **target** to focus a search field when a search button is clicked, or **clear** to remove focus when a menu closes.
## Previewing focus in the editor
When you play your file, the editor draws brackets around the element that has focus. Toggle **Focus Indicator** in the viewport options to show or hide them.
To move focus without a keyboard, click the **Focus** button (the remote icon) in the state machine panel's toolbar to open the Focus Remote. It moves focus in the playing artboard the way a keyboard or gamepad would:
* **Arrows** move focus up, down, left, or right.
* **Next** and **Previous** step through the focus order.
* **Clear** removes focus.
To send keys to your file instead of triggering editor shortcuts, press **Option+Space** to play with keyboard capture on, or click **Toggle Keyboard Capture** in the playback header.
## Focus and screen readers
Elements with a focus node automatically get the **Focusable** trait in the [Semantics](/docs/editor/accessibility/semantics) panel. Combine focus with semantics so assistive technologies can describe the focused element, such as announcing it as a button with a label.
# Reduced Motion
Source: https://rive.app/docs/editor/accessibility/reduced-motion
Make Rive animations more comfortable for users who prefer reduced motion.
Reduced motion preferences let users request less non-essential motion in apps and operating systems.
Rive can’t automatically decide which motion should be reduced because motion may be decorative, functional, or part of the meaning of an interaction. To support reduced motion, pass the user’s motion preference into your Rive file with a data binding property, such as `prefersReducedMotion`. Then use that property to decide how your state machine, timelines, and bound properties should behave.
> [!NOTE]
>
> Reduced motion preferences are usually detected by the app or platform, then passed into the Rive file at runtime. For web, this often starts with the `prefers-reduced-motion` media feature. See [MDN’s `prefers-reduced-motion` documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/%40media/prefers-reduced-motion) for accessibility guidance.
## Common strategies
### Use a separate reduced-motion path
For complex interactions and decorative motion, create separate state machine paths for full motion and reduced motion. Use a `prefersReducedMotion` Boolean property to choose which path runs.
### Reduce or disable animation speed
For simpler cases, bind transition durations, timeline speeds, or animation speeds to a property that changes when reduced motion is enabled.
For example, full motion might use a normal speed value, while reduced motion uses `0` or a lower value.
> [!TIP]
>
> Use [Converters](/docs/editor/data-binding/converters) to convert your `prefersReducedMotion` boolean to a value of 0.
>
> **1. Create a new converter**
>
> Create a new converter group called `BooleanToSpeed`.
>
> 
>
> **2. Add a Toggle converter**
>
> This will toggle the boolean so that when `prefersReducedMotion` is `true`, the output will be `false`.
>
> 
>
> **3. Add a Convert to Number converter**
>
> This transforms a `boolean` to a number where `true = 1` and `false = 0`.
>
> 
>
> **4. Data bind the animation speed**
>
> With the nested component selected, data bind the **Speed** value to `prefersReducedMotion` and add the `BooleanToSpeed` converter.
>
> 
>
> Now when `prefersReducedMotion` is `true`, the animation speed will be 0.
### Replace motion with non-motion feedback
Reduced motion does not always mean removing feedback. Instead of movement, scale, rotation, or bounce, use changes in opacity, or color.
### Reduce distance
Large spatial movement can be difficult even when it is slow. Consider reducing the distance an object travels, or replacing large movement with a small offset and fade.
## Runtime setup
At runtime, use [data binding](/docs/runtimes/data-binding) to pass the user’s motion preference into the Rive file.
> [!NOTE]
>
> In the future, runtimes may expose a built-in reduced motion value that can be read directly by the `.riv` file. For now, pass the user’s motion preference into the file yourself.
The Rive file should use that property to control state machine transitions, timeline speeds, or bound animation properties.
> [!NOTE]
>
> Rive does not automatically apply reduced motion. File authors need to decide which motion is essential, which motion is decorative, and what the reduced-motion experience should be.
# Semantics
Source: https://rive.app/docs/editor/accessibility/semantics
Make your experiences accessible to screen readers by defining semantic types, properties, states, and actions
> [!NOTE]
>
> See [Feature Support](/docs/feature-support#semantics) for the runtimes and versions that support semantics.
Semantics describe what an element is and how it should be understood. Adding semantics makes your experiences accessible, allowing screen readers to correctly describe and navigate your content.
**Architecture: Role / Trait / State / Actions**
* [Role](#semantic-role) — what the node is (button, checkbox, tab, etc.)
* [Properties](#semantic-properties) — additional information like label, value, or hint
* [Traits](#traits) — what the node can do (expandable, selectable, checkable, etc.)
* [State](#state) — what the node is doing (expanded, selected, checked, etc.)
* [Actions](#actions) - interactions triggered by the user (tap, increase, decrease)
> [!NOTE]
>
> **Semantics at Runtime**
>
> At runtime, semantics are converted into the platform’s accessibility system.
>
> On web, this creates accessible DOM elements (for example, divs with roles and attributes). On iOS and Android, a semantic tree is generated and exposed to the system’s accessibility APIs.
>
> Rive handles mapping your semantics to each platform automatically. For details on which runtimes currently support semantics, see [Feature Support](/docs/feature-support).
## Adding semantics

**1. Add Semantics**
Select an element in your scene. In the right sidebar, click the `+` button in the **Semantics** panel to enable semantics for that element.
**2. Choose a Role**
Use the dropdown to assign a [semantic role](#semantic-role), such as button, image, or heading.
**3. Configure Properties**
Update the element’s [semantic properties](#semantic-properties), [Traits](#traits), and [State](#state).
### Semantic role
The semantic role defines what the element *is* (for example, a button or image). Screen readers use this to describe the element and determine how it should behave.
Each role has different available [properties](#semantic-properties).
If your element doesn’t match a specific role, you can leave it set to **None**.
> [!NOTE]
>
> Some elements, like text, automatically infer their semantic role. See [Semantic Inference](#semantic-inference) for more info.
## Semantic properties
Semantic properties provide additional information about an element, such as its label, value, or hint.
Available properties vary depending on the selected semantic role.
### Label
The label describes what the element is or does. This is what screen readers announce.
For example, a slider that controls volume might have the label:
`Volume`
> [!NOTE]
>
> Text elements automatically use their text content as the label. See [Semantic Inference](#semantic-inference) for more info.
### Heading (text only)
Text elements can be marked as headings to define structure and hierarchy.
Options include **None** and **Heading 1** through **Heading 6**.
Headings help screen reader users navigate your content more easily.
> [!NOTE]
>
> On web, Heading 1 maps to an `` element, Heading 2 to ``, and so on.
### Value (inputs only)
Some elements, like sliders and switches, have a **Value** property that reflects their current state.
For example, a volume slider might have a value of `70%`.
Use data binding to keep the semantic value in sync with the visual state.
***
## Traits
Traits define what an element *can do*, while states describe what it is doing right now.
Some semantic roles include traits, such as **expandable** or **selectable**. Enabling a trait makes its corresponding [state](#state) available.
The lock icon indicates a required trait for that semantic role. For example, a checkbox always includes the **selectable** trait.
***
## State
States represent the current value of the node.
For example, an element with the **selectable** trait will have a **selected** state.
Some state flags are only meaningful when their corresponding trait is set. Without the trait, the platform sees the property as not applicable.
Keep semantic states in sync with your Rive file. For example, bind a boolean from your view model to the **toggled** state of a switch. You could also key the **toggled** state in a timeline.
States that come from a trait show three options: **N/A** means the trait is off, and **No** and **Yes** set the state.
### Expanded
Whether screen readers report the element as expanded. Choose **N/A** if it doesn't expand, **No** if it's collapsed, or **Yes** if it's expanded.
### Checked
Whether screen readers report the element as checked. Choose **No** for unchecked or **Yes** for checked. Checkboxes also have **Mixed**, for a partly checked state.
### Required
Whether screen readers report a field as required. Choose **N/A** if it's never required, **No** if it's optional, or **Yes** if it's required.
### Hidden
Hides the element from the accessibility tree.
> [!NOTE]
>
> Elements that are not visible (for example, hidden by layout or soloing) are automatically removed from the accessibility tree and do not require this property.
>
> Use **Hidden** when an element is still present in the scene (for example, opacity is set to 0) but should not be exposed to assistive technologies.
### Disabled
Marks the element as disabled and not interactive.
### Live Region
Indicates that the element’s content may update dynamically and should be announced by screen readers.
### Obscured (text fields only)
Screen readers don't read the field's content aloud. Use it for password fields.
### Multiline (text fields only)
Screen readers report the field as accepting multiple lines of text.
### Modal (dialogs only)
Screen readers stay inside the dialog until it closes. Available on the **Dialog** and **Alert dialog** roles.
## Actions
Semantic actions are interaction events triggered by assistive technologies. You can listen for these actions and update your experience in response.
### Adding an action
**1. Create a Listener**
Select your object and [create a new Listener](/docs/editor/state-machine/listeners).
**2. Listen to a Semantic Action**
With your listener selected, in the right sidebar choose **Semantic Action** in the **Listen to** dropdown.
**3. Set the action type**
Select the [action type](#types-of-actions) to listen for.
### Types of actions
Actions include **tap**, **increase**, and **decrease**. Additional actions may be added in future releases.
#### Tap
Represents activating an element (similar to a click).
When a user activates an element using a screen reader, a **tap** action is triggered. You should listen for this action and handle it the same way as a standard click or pointer interaction.
> [!NOTE]
>
> It’s common to add both a **Click** and a **Semantic Tap** listener to the same element to support pointer and assistive interactions.
#### Increase / decrease
Used for adjustable elements like sliders.
Users trigger these actions through assistive technologies—for example, by focusing a slider and swiping up or down with a screen reader, or using arrow keys on a keyboard.
You should listen for **increase** and **decrease** and update your value accordingly.
### Semantic inference
Some roles and properties are inferred based on the element they are applied to.
For example, when adding semantics to a text element, the [Role](#semantic-role) is set to **Text**, and the [Label](#label) is read from the element’s text content. Screen readers announce this label. You can't edit an inferred label in the Inspector; change the text instead.
***
## Testing semantics
Adding semantics is only the first step. You should always test your experience at runtime to make sure it behaves as expected.
Small issues—like a missing label or incorrect state—can make elements confusing or unusable for screen reader users.
### Runtime testing
The best way to test semantics is by using a screen reader.
* **macOS / iOS**: VoiceOver
* **Android**: TalkBack
* **Windows**: Narrator or NVDA
Turn on a screen reader and navigate through your experience:
* Move between elements
* Listen to how each element is announced
* Interact with buttons, sliders, and inputs
### What to check
As you test, pay attention to:
* **Labels** — Does each element clearly describe what it is or does?
* **Role** — Is the correct role announced (button, heading, etc.)?
* **Value** — Do dynamic elements (like sliders) report the correct value?
* **State** — Are states like selected, disabled, or expanded accurate?
* **Order** — Does navigation follow a logical flow?
# AI Agent
Source: https://rive.app/docs/editor/ai-agent/ai-agent
Use Rive's built-in AI agent to design, animate, and write code in your file from a prompt.
Rive's AI agent works inside the Editor, in the file you have open. Describe what you want, and it builds it: shapes, layouts, components, view models, animations, state machines, and scripts. You can watch each change on the stage as the agent makes it, then keep editing by hand or ask for more changes.
> [!NOTE]
>
> Every plan includes the agent. Free and Cadet plans have usage limits that refill over time. Voyager and Enterprise plans include monthly credits, more advanced models, and top-up credits. See [Plans and pricing](/docs/account-admin/pricing).
## Opening the agent
Click the **Agent** tab in the left sidebar, or press `Cmd + 5` (macOS) or `Ctrl + 5` (Windows).

* **Chat dropdown**: Switch between your chats.
* **+**: Start a new chat. Your other chats are kept.
* **Panel Options** (**•••**): Close the current chat, close the other chats, clear all chats, or open the chat in the stage area.
### Opening the agent in the stage area
For more room, open a chat as a tab in the stage area, next to your artboards:
**Step 1**
In the Agent tab, click **Panel Options** (**•••**).
**Step 2**
Choose **Open in Viewport**.
The chat moves to a tab in the stage area, and the Agent tab in the sidebar closes.
### Starting a new file with the agent
When you click **New File** in the File Browser, a prompt opens so the agent can build the file for you.
* **Prompt** - describe the file you want. Leave it empty to make a blank file.
* **Examples** - fill the prompt with an example to try. Some start from a template file.
* **Launch agent** - creates the file and starts the agent on it with your prompt. With an empty prompt, the button becomes **Create blank** and makes a blank file.
* **Don't ask again** - skip this prompt so **New File** always makes blank files. Turn it back on with the **New File Prompt** (sparkle) button in the File Browser toolbar.
#### Free kickstart
A free kickstart is a free agent build for a new file, with a shorter prompt limit. Once you use it, it recharges over time. Until then, you can only create blank files from this prompt.
## Writing a prompt
Type what you want in the prompt box at the bottom of the panel and press `Enter`. Be specific about what should change and how it should behave.
> Create a script that draws a rounded rectangle. Width, height, color, and corner radius should be inputs. When the inputs change, the drawing should update.
The agent replies with a summary of what it changed, shows each step it took, and explains anything it created, such as a new script in the **Assets** panel.
You can also attach an image to your prompt, such as a reference or a sketch. Not every model supports images.
### Ask and Build
Choose a mode below the prompt box:
* **Build** designs, animates, and writes code in your file. It uses credits faster.
* **Ask** answers questions about your file or about how to use Rive, without changing anything. It uses fewer credits.
### Model and effort
Choose the model and the effort level, **Small**, **Medium**, or **Large**, below the prompt box. Higher effort can handle bigger requests, but uses more credits. Advanced models are available on Voyager and Enterprise plans.
On Voyager and Enterprise plans, admins can add your workspace's own API keys for select model providers, so usage is billed to your provider account instead of your Rive credits. Choose **API keys** from the model menu.
## What the agent can do
The agent works in the open file. It can:
* **Design**: Create shapes, paths, and vector artwork, and import SVGs.
* **Build layouts**: Create [layouts](/docs/editor/layouts/layouts-overview) and [groups](/docs/editor/fundamentals/groups).
* **Use components**: Create and arrange [components](/docs/editor/fundamentals/components).
* **Rig**: Add [bones](/docs/editor/manipulating-shapes/bones) and [meshes](/docs/editor/manipulating-shapes/meshes).
* **Animate**: Create timelines and keys, [state machines](/docs/editor/state-machine/state-machine), and [listeners](/docs/editor/state-machine/listeners).
* **Bind data**: Create [view models](/docs/editor/data-binding/overview), properties, and [property groups](/docs/editor/data-binding/property-groups).
* **Write code**: Create and edit [scripts](/docs/scripting/getting-started) and [shaders](/docs/scripting/wgsl-shaders), run tests, and read the console to fix errors.
* **Manage assets and tags**: Work with the file's assets and [tags](/docs/editor/tagging).
* **Inspect the file**: Find objects and read their properties, so it can answer questions about the file.
## Reviewing script changes
When the agent edits a script, its changes are shown as a diff in the script editor until you review them. Scripts with pending changes are listed in the [Changes tab](/docs/editor/interface-overview/debug-panel#changes) of the Debug Panel.
* **Previous** and **Next** - jump between blocks of changes. The counter shows the current block and the total in this script.
* **Accept** and **Reject** - keep or undo a single block of changes.
* **Accept All** - keep every change the agent made to this script and clear the diff.
* **Reject All** - undo every change the agent made to this script, restoring the removed lines.
## Credits
The agent is billed in AI credits, which are expressed in USD: \$1 in credits is \$1 of AI usage.
Each paid seat adds monthly credits to your workspace:
* **Voyager**: \$20/seat/month
* **Enterprise**: \$40/seat/month
Credits are shared across the workspace:
* Monthly credits reset each month and don't roll over.
* Monthly credits are always used before top-up credits.
* Top-up credits don't expire.
When the workspace runs out of credits, the agent stops accepting new prompts until the monthly credits reset or an admin adds top-up credits. On Free and Cadet plans, usage refills over time instead.
### Adding credits
Workspace admins on Voyager and Enterprise plans can buy top-up credits.
**Step 1**
On the **Home** tab, click the dropdown next to the workspace name and choose **Admin**.
You can also click **Usage** on the **Agent credits** card.
**Step 2**
On the **Overview** tab, find the **Top-up credits** card and click **Purchase credits**.
**Step 3**
Choose an amount and complete the purchase.
The **Monthly credits** card next to it shows how much of this month's credits are left and when they reset.
## FAQ
> [accordion] Is my code or project data used to train the AI or any other LLMs?
>
> No. We have a Zero Data Retention policy active with our LLM provider. Neither we nor the provider use user data to train AI models.
> [accordion] Can I disable the agent for my workspace?
>
> Admins on Enterprise workspaces can turn the agent on or off for the entire workspace at any time.
> [accordion] Will the AI make mistakes?
>
> Yes. Like any AI system, the agent can make incorrect or suboptimal changes, though it tries to check and correct its work. Always review what it creates, especially code.
> [accordion] Can I provide feedback on the AI's responses?
>
> Yes. Please send feedback to our [Community](https://community.rive.app/).
# AI Agent vs CLI
Source: https://rive.app/docs/editor/ai/agent-vs-cli
Choose between Rive's built-in AI Agent and the Rive CLI with your own coding agent.
There are two ways to have AI build with Rive:
* The **[AI Agent](/docs/editor/ai-agent/ai-agent)** is built into the Rive Editor and works in the file you have open.
* The **[Rive CLI](/docs/cli/overview)** lets your own coding agent, such as Claude Code or Cursor, build Rive projects on disk.
| | AI Agent | Rive CLI |
| - | - | - |
| **Where you prompt** | Inside the Rive Editor | Your own coding agent, such as Claude Code or Cursor |
| **What it changes** | The file open in the Editor | Project files on disk, including Rive Markup Language (.rml), which build to `.riv` and `.rev` files |
| **Model and billing** | Rive credits, or your workspace's own API keys | Your coding agent's plan |
| **Best for** | Quick help while you design, animate, and code in the Editor | Working from your code editor, version control, and CI, without opening the Editor |
# Rive MCP Integration
Source: https://rive.app/docs/editor/ai/mcp
> [!NOTE]
>
> MCP integration is currently available only in the desktop Editor for Windows and macOS.
You can connect the Rive Editor to AI tools through MCP (Model Context Protocol). The first set of tools are designed to let AI handle repetitive tasks, like creating complex View Models, State Machines with hundreds of states/layers, Layouts, Shapes, and more.
[YouTube video player](https://www.youtube.com/embed/_a2Y4vzuGAs)
### Supported features
* **Create and manage Rive files** — add, rename, resize, arrange, and focus artboards.
* **Inspect and edit the scene** — query hierarchies, select objects, update properties, rename, duplicate, reorder, reparent, or delete elements.
* **Build designs** — create shapes, paths, layouts, component instances, component lists, and asset-based elements.
* **Rig with bones** — create root bones and bone chains, by length and rotation or by head and tail points, then bind and weight them.
* **Create animation and interaction** — edit linear animations, state machines, states, transitions, conditions, keyframes, and interpolation.
* **Work with data binding** — create view models, properties, instances, bindings, and custom property groups.
* **Edit scripts and shaders** — manage Luau scripts and WGSL shaders, update source code, run diagnostics, recompile, test, search code, and read console output.
> [!NOTE]
>
> This list of features will evolve over time as more tools are added.
Edits that would make runtimes refuse or crash on the file, like two colors on one fill or a gradient outside a fill or stroke, are refused and undone. Colors are read the same way as the hex field: `#fff` is white, and names like `red` are refused.
## Installation
### Using Cursor
**1. Open Rive**
Install and open the latest version of the [Rive](https://rive.app/downloads) desktop app for Mac or Windows.
**2. Set up Cursor**
Create a [Cursor](https://www.cursor.com/) account and install the app.
**3. Open Cursor settings**
Open Cursor and navigate to the settings panel in the top right corner.

**4. Add custom MCP**
Open the Tools & MCPs tab and click Add Custom MCP.

**5. Save the configuration**
Save the following JSON snippet to your computer as `mcp.json`.
```json theme={null}
{
"mcpServers": {
"rive": {
"url": "http://127.0.0.1:9791/mcp"
}
}
}
```
**6. Enable connection**
Turn the MCP connection `On`
**7. Verify connection**
If everything was installed correctly, you should see Rive as an available MCP server.

> [!NOTE]
>
> For the Rive server to be available, you must have the Rive desktop app open.
Additional information on setting up MCP can be found [here](https://cursor.com/docs/mcp).
### Using Claude in Terminal
[YouTube video player](https://www.youtube.com/embed/5_h51PdNhsU)
**1. Open Rive**
Install and open the latest version of the [Rive desktop app](https://rive.app/downloads) for macOS or Windows.
**2. Add the MCP server**
Run the following command in your terminal:
```shell theme={null}
claude mcp add --transport http rive http://127.0.0.1:9791/mcp
```
**3. Start Claude**
Run Claude and follow the prompts:
```shell theme={null}
claude
```
## What can it do?
Once your AI tool is connected, it's time to start prompting the AI.
**1. Open your Rive file**
Have a Rive File open and an Artboard created.
**2. Enter your prompt**
Type your prompt into the chat UI and hit enter. The AI will take a moment to process the request, and its changes appear in the open Rive file.
Example prompt:
```
Create a State Machine about birds with 20 states and 2 layers
```
# Animation
Source: https://rive.app/docs/editor/animate-mode/animate-mode-overview
How animation works in Rive: timelines of keys, interpolation between them, and state machines that decide what plays.
Animation in Rive is built from a few parts that work together:
* A **[timeline](/docs/editor/animate-mode/timeline)** is a single animation, such as an idle loop or a button press.
* **[Keys](/docs/editor/animate-mode/keys)** on a timeline store a property's value at a point in time, like a ball's Y position at frame 0 and frame 30.
* **[Interpolation](/docs/editor/animate-mode/interpolation-easing)** fills in the values between two keys, and decides how the motion eases. Use the [Graph Editor](/docs/editor/animate-mode/graph-editor) to shape it as a curve.
* A **[state machine](/docs/editor/state-machine/state-machine)** decides which timelines play at runtime, and blends and transitions between them in response to data and user input.
You create timelines, keys, and state machines in Animate mode. Switch modes with the toggle in the toolbar, or press `Tab`. See [Design and Animate Modes](/docs/editor/fundamentals/design-vs-animate-mode).
> [!WARNING]
>
> In Animate mode, editing an object while a timeline is selected can create keys. Make design changes in Design mode instead. If you do happen to make design changes in Animate mode, you can apply those changes to design mode by right clicking the object and selecting "Apply all to design mode". You can find the same option under the ellipsis menu in the top left of the timeline ui.
[YouTube video player](https://www.youtube.com/embed/4U3er1uSjBw)
## Animations panel
The **Animations** panel (Cmd/Ctrl + 4 ) lists the timelines and state machines on the active artboard. Use it to create, select, and organize them.
* **Search**: Click the search button in the panel header to filter the list by name.
* **Options**: Click the panel options button to filter the list to state machines or timelines, manage [tags](/docs/editor/tagging), and choose a sort:
* **Custom**: Drag items into your own order and folders.
* **Type**: Group items into state machines and timelines.
## Motion without keys
Not all motion needs keys. These features move objects on their own, or drive timelines for you:
* **[Constraints](/docs/editor/constraints/constraints-overview)**: Make an object follow, aim at, or copy another object.
* **[Joysticks](/docs/editor/manipulating-shapes/joysticks)**: Blend timelines from a single handle, such as turning a head.
* **[Data binding](/docs/editor/data-binding/overview)**: Drive properties directly from values your app sets at runtime.
* **[Scripting](/docs/scripting/getting-started)**: Animate with code.
## Learn more
> [card] [Timeline](/docs/editor/animate-mode/timeline)
>
> Create timelines, control playback, and set how an animation loops and how long it runs.
> [card] [Keys](/docs/editor/animate-mode/keys)
>
> Set, select, move, copy, and stagger the keys that make up an animation.
> [card] [Interpolation](/docs/editor/animate-mode/interpolation-easing)
>
> Control how values change between keys, from linear to eased to hold.
> [card] [Graph Editor](/docs/editor/animate-mode/graph-editor)
>
> See and edit how property values change over time as curves.
> [card] [State Machines](/docs/editor/state-machine/state-machine)
>
> Decide which timelines play, and blend and transition between them.
> [card] [Custom Draw Order](/docs/editor/animate-mode/animating-draw-order)
>
> Key draw order rules to change what draws on top during an animation.
## Example: a bouncing ball
This video animates a bouncing ball, covering keys, interpolation, and a couple of classic animation principles.
[YouTube video player](https://www.youtube.com/embed/DitdOy_HxKc)
# Animating Draw Order
Source: https://rive.app/docs/editor/animate-mode/animating-draw-order
You can change the draw order of your graphics at design time by moving items up and down the [Hierarchy](/docs/editor/interface-overview/hierarchy)– but what if you want to change the draw order during an animation? Or what if you want to change the draw order without breaking the current hierarchical structure? Rive allows you to accomplish this with Draw Order Rules.
[YouTube video player](https://www.youtube.com/embed/6J3JIwgUwe0)
## Draw Order rules
To animate the draw order of a group or shape, start by selecting it. Use the Draw Order section of the Inspector to create Draw Order Rules.
> [card] [Learn by remixing](https://rive.app/community/files/26116-animating-draw-order?utm_source=docs\&utm_medium=docs_link_card\&utm_campaign=docs_to_marketplace_links)
>
> Open this file on Marketplace, then click Remix to experiment in the Rive Editor.

The Normal rule is the default order (based on [Hierarchy](/docs/editor/interface-overview/hierarchy) order). When the radio button next to this rule is active, the shape appears at its default draw order.
Draw Order Rules allow you to select a target (note that this must be a drawable item, not a group) and whether to draw above or below the target.
> [!NOTE]
>
> The target must be a drawable item, like a shape. It cannot be a group.
If a rule conflicts with another, such as two objects each set to draw above the other, Rive can't resolve the order. A warning icon with a **Cyclic dependency** tip appears next to the rule. Change or remove one of the rules to fix it.
In Animate mode, use the radio button next to the Draw Order Rules to set a key. Note that these are [Hold keys](/docs/editor/animate-mode/interpolation-easing#interpolation-types) as Draw Order cannot be interpolated.

# Graph Editor
Source: https://rive.app/docs/editor/animate-mode/graph-editor
See and edit how property values change over time as curves.
[YouTube video player](https://www.youtube.com/embed/yfC6_1yS_vE)
The Graph Editor shows each keyed property as a curve, with time on the horizontal axis and the property's value on the vertical axis. Where the timeline shows when your keys happen, the Graph Editor shows what the value does between them, so you can see the shape of your motion at a glance.
You can move keys in time and value, add keys on a curve, and shape [Cubic Value](#cubic-vs-cubic-value) curves with Bezier handles, similar to the graph editor in After Effects.
## Opening the Graph Editor
Click the Graph Editor button in the timeline toolbar, or press Shift + F3 . The Graph Editor replaces the timeline. Click the button again to go back to the timeline.
You can also click **Open graph editor** in the Interpolation panel.
## Choosing which curves to show
The Graph Editor shows the keyed properties of the objects you select on the stage or in the Hierarchy.
To focus on a single property, click it in the property list on the left of the Graph Editor. Shift -click to add or remove more properties.
## Value and Speed Graphs
The Graph Editor has two views of the same keys:
* **Value Graph** plots each property's value at each moment. Use it to see where a property is over time, and to add keys or change their values.
* **[Speed Graph](/docs/editor/animate-mode/speed-graph)** plots how fast each value is changing, in units per second. Use it to see where motion speeds up and slows down, and to shape the ease in and out of each key.
Switch between them with the **Value** | **Speed** toggle in the options bar at the bottom of the Graph Editor, or press Shift + G . Both views edit the same keys and handles, so switching never changes your animation.
To see how fast each property changes instead of its value, switch to the [Speed Graph](/docs/editor/animate-mode/speed-graph).
## Cubic vs. Cubic Value
Both [interpolation types](/docs/editor/animate-mode/interpolation-easing) draw a curve between keys, but only Cubic Value has handles you can drag in the Graph Editor.
* **Cubic** works like a cubic Bezier easing curve in CSS. It shapes how fast the value changes over time, but it always lands exactly on the values you keyed. You edit it in the [Interpolation panel](/docs/editor/animate-mode/interpolation-easing#setting-the-interpolation-on-keys); the Graph Editor only displays it.
* **Cubic Value** gives each key draggable Bezier handles in the Graph Editor. Because the handles store both time and value, the curve can overshoot a key's value before settling on it. It uses a little more data than Cubic.
That overshoot is the key difference. Animating a property from 0 to 0 with Cubic produces no motion at all. With Cubic Value, you can pull the handles so the curve travels past 0 and back, creating real movement even when the start and end values are identical. This makes Cubic Value ideal for bounces, anticipation, and other effects that push beyond the final value.
> [!TIP]
>
> To switch selected keys to Cubic Value, press F9 for ease in and out, Shift + F9 for ease in, or Cmd/Ctrl + Shift + F9 for ease out.
## Editing curves
### Moving keys
Drag a key up or down to change its value, or left or right to change its time. Hold Shift while dragging to lock the movement to one axis.
To add a key on the Value Graph, hover over a curve until the pen cursor appears, then click.
### Shaping a curve with handles
**Step 1**
Select the keys you want to shape and set their interpolation to **Cubic Value**.
**Step 2**
Drag a handle to change the curve. Handles on either side of a key are mirrored, so the curve stays smooth through the key.
**Step 3**
To move one handle without its partner and create a sharp change in direction, hold Alt while dragging.
While dragging a handle, hold Shift to lock it to one axis, or press Esc to cancel the drag.
To set handles to exact values, select them. Fields appear in the options bar at the bottom of the Graph Editor: **Value** and **Ease** on the Value Graph, or **Speed** and **Ease** on the Speed Graph. Typing a value applies it to every selected handle, which is an easy way to give several keys the same ease.
### Auto Bezier
Cubic Value keys can set their handles automatically to create a smooth curve through the surrounding keys. Turn on **Apply auto bezier** in the Interpolation panel, and use **Auto bezier coefficient** to control how strong the curve is. Dragging a handle turns auto bezier off for that key.
### Shortcuts
| Shortcut | Result |
| - | - |
| Shift + click | Add keys or handles to the selection |
| Shift + drag | Lock a key or handle to one axis |
| Alt + drag a handle | Break the mirroring between a key's handles |
| Cmd/Ctrl + drag | Turn off snapping |
| Esc while dragging a handle | Cancel the drag |
## Navigating the graph
The options bar at the bottom of the Graph Editor has two zoom buttons:
* **Fit** (F ) zooms to fit the curves in view.
* **Auto-Zoom Height** (Shift + F ) keeps adjusting the vertical zoom so the curves always fill the height of the graph.
Hold Space and drag to pan.
# Interpolation (Easing)
Source: https://rive.app/docs/editor/animate-mode/interpolation-easing
Control how a value changes between two keys, from steady motion to holds, eases, and bounces.
When you set two keys on a property, Rive calculates the values in between. This is called interpolation. The interpolation type, often called easing, controls how the value gets from one key to the next: at a steady rate, speeding up and slowing down, bouncing past the target, or jumping straight to it.
Interpolation is set on the key where a change starts, and applies until the next key.
[YouTube video player](https://www.youtube.com/embed/9xguOdcuhOo)
## Interpolation types
* **Hold** doesn't interpolate. It keeps the current value until the next key, then jumps to the new value instantly.
* **Linear** changes the value at a constant rate. It's the default for new keys.
* **Cubic** follows a curve that you shape with two handles. The default curve changes slowly at the start and end and fastest in the middle. Cubic always moves between the values you keyed and never past them.
* **Cubic Value** is like Cubic, but you shape it with Bezier handles in the [Graph Editor](/docs/editor/animate-mode/graph-editor), and the curve can overshoot a key's value before settling on it.
* **Elastic** overshoots the value and oscillates before settling on it, like a spring.
| Shortcut | Interpolation |
| - | - |
| F6 | Hold |
| F7 | Linear |
| F8 | Cubic, ease in and out |
| Shift + F8 | Cubic, ease in |
| Cmd/Ctrl + Shift + F8 | Cubic, ease out |
| F9 | Cubic Value, ease in and out |
| Shift + F9 | Cubic Value, ease in |
| Cmd/Ctrl + Shift + F9 | Cubic Value, ease out |
| F10 | Elastic |
## Setting the interpolation on keys
**Step 1**
Select one or more keys on the timeline.
**Step 2**
Choose an interpolation type at the top of the Interpolation panel, to the right of the timeline. The same options are in the **Keyframe Interpolation** section of the Inspector.

You can also right-click the keys and choose a type from the **Interpolation** menu, or use one of the [shortcuts](#interpolation-types).
**Step 3**
Adjust the curve or options for the type you chose. See below.
> [!TIP]
>
> If the Interpolation panel is hidden, click the curve icon next to the timeline tabs to show it.
The graph in the Interpolation panel shows how the value changes from the selected key to the next one. Time runs along the horizontal axis, and the change in value runs up the vertical axis. The vertical blue line marks the current moment.
### Cubic options
Drag the two handles on the graph to shape the curve. You can drag them as far as you want up or down; the graph zooms out to keep them in view.
The field below the graph shows the curve as four numbers: the horizontal and vertical positions of the first handle, then the second, like a CSS `cubic-bezier()` value. Type your own values, separated by commas or spaces, to match an easing from a brand's motion guidelines or another tool. You can also copy them to reuse elsewhere.

### Cubic Value options
Shape Cubic Value curves by dragging their handles in the [Graph Editor](/docs/editor/animate-mode/graph-editor). In the Interpolation panel, you can click **Open graph editor**, or turn on **Apply auto bezier** to set the handles automatically for a smooth curve through the surrounding keys. **Auto bezier coefficient** controls how strong that curve is.
### Elastic options
* **Easing**: Where the oscillation happens. **Ease In** oscillates at the start, **Ease Out** at the end, and **Ease In Out** at both.
* **Amplitude**: How far the value overshoots.
* **Period**: How quickly the oscillation settles.
## Default interpolation
The default interpolation is the type that new keys use. It starts as Linear.
To set it from a key:
**Step 1**
Select a key that uses the interpolation you want.
**Step 2**
In the Interpolation panel, click **Set as default**.

To set it from the Inspector:
**Step 1**
Deselect everything. The Inspector shows **Default Interpolation**.
**Step 2**
Choose the interpolation type and options you want new keys to use.

## The Graph Editor
To see and edit interpolation as curves on a graph, use the [Graph Editor](/docs/editor/animate-mode/graph-editor).
# Keys
Source: https://rive.app/docs/editor/animate-mode/keys
Set, select, move, resize, stagger, copy, and bind the keys that make up an animation.
A key, or keyframe, stores a property's value at a point in time on a [timeline](/docs/editor/animate-mode/timeline). When a property has two or more keys, Rive [interpolates](/docs/editor/animate-mode/interpolation-easing) the values between them to create motion.
[YouTube video player](https://www.youtube.com/embed/BiaWH6rHd7o)
## Setting keys
With a timeline selected in Animate mode, move the playhead to the time you want, then set a key in any of these ways:
* Move, rotate, or scale an object on the stage. Rive keys each property that changes.
* Change a property's value in the Inspector.
* Click the key button next to a property in the Inspector to key its current value.
Once a property is keyed, the object and the property appear as rows on the timeline.

The key button shows the property's state at the playhead:
* **Grey outline**: The property isn't animated in this timeline.
* **Colored outline**: The property is animated, but there's no key at the playhead.
* **Filled**: There's a key at the playhead.
> [!WARNING]
>
> While a timeline is selected, changing a property creates a key. See [Design and Animate Modes](/docs/editor/fundamentals/design-vs-animate-mode) to learn how to avoid accidental keys.
## Selecting keys
* Click a key to select it. Shift -click to add or remove keys.
* Drag across the timeline to select every key in an area.
* Click a key on an object's row to select the keys of all of that object's properties at that time.
Keys on a property's row are blue. Keys on an object's row, or on a collapsed row, are grey and stand for all the keys beneath them.
Some objects also have group rows that collect related keys, such as keyed vertices, constraints, nested animations, or grid tracks.
### Row menu
Right-click a row on the timeline for commands that act on the keys that row covers. Right-click an empty part of the timeline, or the **All Keys Row**, to act on the whole timeline.
* **Select All Keys**: Select every key the row covers.
* **Select Keys Before Playhead** / **Select Keys After Playhead**: Select the keys at or before, or at or after, the playhead.
* **Key All at Playhead**: Key every animated property the row covers at the playhead.
* **Delete Keys at Playhead**: Delete the keys the row covers at the playhead.
* **Remove Redundant Keys**: Delete keys that don't change the animation, like repeats of the same value. It applies to the selected keys, or to the row if no keys are selected.
## Moving keys
Drag selected keys left or right to change when they happen. Drag a grey key to move every property on that row at once, or a blue key to move a single property.

To move the playhead between keys, press Cmd/Ctrl + , or Cmd/Ctrl + . .
## Resizing keys
To speed up or slow down part of an animation, select two or more keys, hold Alt , and drag the first or last selected key. The keys in between spread out or squeeze together to match.

## Staggering keys
To offset the same motion across several objects, so each one starts a little after the last, select the keys, hold Cmd/Ctrl + Alt , and drag. Each object's keys shift by a growing amount, in the order the rows appear on the timeline.
When the rows are expanded, each property's keys stagger separately. When they're collapsed, each object's keys move together.
## Copying and pasting keys
Copy selected keys with Cmd/Ctrl + C . Then select a destination and press Cmd/Ctrl + V . The keys are pasted at the playhead.
* To reuse the same motion on another object, select that object and paste. Rive pastes keys onto the matching properties and skips any the object doesn't have.
* To copy keys from one property to another, such as from X to Y, select the destination property's row and paste.
## Reversing keys
To play a section of an animation backward, select the keys, right-click, and select **Reverse keys**.
## Setting the interpolation
To control how a value changes between two keys, select the first key and choose its [interpolation](/docs/editor/animate-mode/interpolation-easing). You can also right-click keys and choose a type from the **Interpolation** menu.
## Binding key values
You can [data bind](/docs/editor/data-binding/overview) the value stored in a key. This lets a keyed value come from data instead of being fixed on the timeline.
**Step 1**
Right-click the key you want to bind.
**Step 2**
Select **Data Bind**.
**Step 3**
Choose the property you want to bind to the key value.
Once bound, the key uses the bound value when the animation reaches that point in the timeline. To change or remove the binding, right-click the key and select **Update Bind** or **Unbind**.
# Motion Paths
Source: https://rive.app/docs/editor/animate-mode/motion-paths
See and shape the path an object travels between its position keys, right on the stage.
A motion path shows the route an object travels between its position keys. In [animate mode](/docs/editor/fundamentals/design-vs-animate-mode), select an object with X or Y position keys, and its motion path appears on the stage as a blue line.
To show or hide motion paths, use the **Tool overlays** options in the stage's [view options menu](/docs/editor/interface-overview/stage#view-options-menu).
## Editing motion paths
You can shape the motion directly on the stage instead of editing keys in the timeline:
* **Keys:** Each position key is a dot on the path. Drag a key to move the object at that frame. Its bezier handles move with it, so the curve keeps its shape.
* **Segments:** Drag the path between two keys to bend it. This adds bezier handles at the keys on either side.
* **Handles:** Drag a bezier handle to bend the path. The opposite handle on the same key mirrors it to keep the path smooth. Hold Alt while dragging to move one handle on its own and make a sharp corner.
Cmd/Ctrl -click a key to smooth the path through it. On a key in the middle of the path, this adds mirrored handles aimed between its neighbors. On the first or last key, it adds a single handle along the path.
Bending the path switches the keys on that segment to [Cubic Value](/docs/editor/animate-mode/interpolation-easing) interpolation. Linear and Cubic easing convert without changing the motion. Other easing types, such as Hold and Elastic, start over from linear. If a key exists on only one axis, Rive adds the missing X or Y key when you edit it on the path.
# Speed Graph
Source: https://rive.app/docs/editor/animate-mode/speed-graph
See how fast each property changes over time, and shape eases by speed.
The Speed Graph is the second view of the [Graph Editor](/docs/editor/animate-mode/graph-editor). The Value Graph plots a property's value at each moment. The Speed Graph plots how fast that value is changing, so you can see where motion speeds up and where it slows down.
Two curves can look almost the same on the Value Graph and still feel different in motion. The Speed Graph shows that difference.
The Speed Graph adds no data to your file. It edits the same keys and handles as the Value Graph, so your animations play back the same in every runtime.
## Switching to the Speed Graph
Open the Graph Editor, then select **Speed** in the **Value** | **Speed** toggle in the options bar at the bottom of the Graph Editor. Select **Value** to switch back.
You can also switch graphs in these ways:
* Press Shift + G to switch between the Value Graph and the Speed Graph.
* Choose **Value** or **Speed** under **Graph** in the [timeline's options menu](/docs/editor/animate-mode/timeline#timeline-options).
If you close the Graph Editor and open it again with Shift + F3 , it shows the graph you used last.
## Reading the Speed Graph
The vertical axis shows speed in the property's units per second, such as degrees per second for rotation or percent per second for scale. Axis labels end in **/s**.
Speed is positive when the value goes up and negative when it goes down. The line at zero is highlighted. On that line, the property isn't moving.
Each interpolation type has its own shape:
* **Hold** draws a flat line at zero, because the value doesn't change until the next key.
* **Linear** draws a flat line, because the value changes at a constant rate.
* **Cubic**, **Cubic Value**, and **Elastic** draw curves.
If the speed going into a key is different from the speed leaving it, the curve jumps at that key. The jump means the speed changes instantly at that moment.
## Editing curves
You can only shape a curve that starts at a key that uses [Cubic Value](/docs/editor/animate-mode/graph-editor#cubic-vs-cubic-value). That curve has two handles: one at its first key and one at the next key. Curves that start at keys with other interpolation types have no handles.
### Dragging handles
On the Speed Graph, each handle sits level with its key, at the speed going into or out of that key.
* Drag a handle up or down to change the speed at that key.
* Drag a handle left or right to change the ease, which is how far the handle's influence reaches toward the neighboring key. The speed stays the same.
When you drag a handle, the handle on the other side of the key changes to the same speed, so the motion doesn't jump at that key. Its ease doesn't change. To change one side only, hold Alt while dragging.
While dragging a handle:
* The handle snaps to zero speed, so you can bring the motion to a full stop. Hold Cmd/Ctrl to turn off snapping.
* Hold Shift to lock the handle to one axis.
* Press Esc to cancel the drag.
### Moving keys
Drag a key left or right to change its time.
Drag a key up or down to change the speed on both sides of the key at once. The key's value stays the same. This changes only the sides of the key that use Cubic Value.
To add a key on a curve, switch to the Value Graph. Clicking a curve on the Speed Graph doesn't add a key.
### Setting exact values
Select one or more handles. The **Speed** and **Ease** fields appear in the options bar at the bottom of the Graph Editor. **Ease** is a percentage.
Typing a value applies it to every selected handle. If the selected handles have different values, the field shows **-**.
### Shortcuts
| Shortcut | Result |
| - | - |
| Shift + G | Switch between the Value Graph and the Speed Graph |
| Alt + drag a handle | Change the speed on one side of a key only |
| Cmd/Ctrl + drag a handle | Turn off snapping to zero speed |
| Shift + drag | Lock a key or handle to one axis |
| Esc while dragging a handle | Cancel the drag |
# Timeline
Source: https://rive.app/docs/editor/animate-mode/timeline
Create timelines, control playback, and set how an animation loops, how long it runs, and how fast it plays.
A timeline is a single animation on an artboard. It records how properties change over time as [keys](/docs/editor/animate-mode/keys), and you can play it on its own or combine it with other timelines in a [State Machine](/docs/editor/state-machine/state-machine).
In Animate mode, the timeline panel shows the selected timeline: its keyed objects and properties on the left, their keys along a time ruler on the right, and playback controls and settings above them. Each artboard has its own timelines, so the panel shows the timelines of the [active artboard](/docs/editor/fundamentals/artboards#active-artboard).
[YouTube video player](https://www.youtube.com/embed/-ftpyjPbHEs)
## Creating a timeline
**Step 1**
Switch to Animate mode and select the artboard you want to animate.
**Step 2**
Click **+** next to the timeline tabs and select **Timeline**.
Every timeline on the artboard is listed in the **Animations** panel (Cmd/Ctrl + 4 ). Right-click a timeline there to duplicate it, delete it, or [add it to the Render Queue](/docs/editor/exporting/exporting-for-video-and-static-design).
Timelines you open appear as tabs above the timeline. Right-click a tab to close it, the other tabs, or every tab to its left or right.
A tab shown in italics is a preview tab. Opening another animation replaces it. Click or drag the tab to keep it open.
## Playing a timeline
Click the play button on the timeline tabs, or press Space , to play and pause the selected timeline. Click or drag on the time ruler to move the playhead.
| Shortcut | Result |
| - | - |
| Space | Play or pause |
| Shift + Space | Play the artboard's default animation |
| , / . | Move the playhead back or forward one frame |
| Cmd/Ctrl + , / Cmd/Ctrl + . | Move the playhead to the previous or next key |
| Cmd/Ctrl + Shift + , / Cmd/Ctrl + Shift + . | Move the playhead to the start or end |
## Animation type
The buttons next to the time display set what happens when the playhead reaches the end of the timeline:
* **One-Shot** plays once and stops at the end. This is the default.
* **Loop** jumps back to the start and plays again, continuously.
* **Ping-Pong** plays to the end, then backward to the start, continuously.
### Work area
The work area limits playback to part of a timeline, so you can focus on one section of a longer animation. Click the **Work Area** button in the timeline toolbar to turn it on, then drag the work area's start and end on the time ruler.
To fit the work area to your keys, select the keys, right-click, and select **Set work area**. With a single key selected, choose whether the work area starts or ends at that key.
To stop the work area from being dragged on the ruler, right-click a key and select **Lock Work Area**. Select **Unlock Work Area** to drag it again.
[YouTube video player](https://www.youtube.com/embed/m-uqQo-6cAU)
## Timeline settings
Click the time display at the top of the timeline to open the timeline's settings.

* **Current**: The playhead's position. Type a time to move the playhead.
* **Duration**: How long the timeline is.
* **Playback Speed**: How fast the timeline plays. The default is 1x. Negative values play the timeline backward.
* **Snap Keys**: The timeline's frame rate, in frames per second. Keys snap to these frames. The default is 60.
* **Quantize**: Plays the timeline at its frame rate instead of updating on every frame the app draws. Turn it on for stepped or choppy motion, like a sprite animation. It's off by default.
* **Display Frames** / **Display Time**: Switches the time display between frames and time.
## Finding objects and properties
When many objects are keyed, these tools help you focus on the rows you need:
* **Search**: Click the search button in the timeline toolbar to filter the rows by name.
* **Show Selected**: Click the Show Selected button to show only the rows for the objects you've selected on the stage or in the Hierarchy.
* **Expand and collapse**: Press U to expand or collapse the rows of the selected objects.
* **Show one property**: With objects selected, press P for position, R for rotation, S for scale, O for opacity, or T for all transform properties to show only those rows. Hold Shift to add more.
## Timeline options
Click the options button in the timeline toolbar for more ways to set up the timeline:

* **Apply all to design mode**: Copies the keyed values at the playhead to the design. Use it when you want the design to match a moment in the animation.
* **All Keys Row**: Shows a row at the top of the timeline with every key in the timeline. **Pin All Keys Row** keeps it in view as you scroll.
* **Object Summary Rows**: Shows each object's keys as a single bar instead of a stack of keys.
* **Preview on Hover**: Shows the frame under the pointer on the stage as you hover over the timeline.
* **Sort**: Orders the rows by the **Hierarchy** or in a **Custom** order.
* **Tags**: Shows [tags](/docs/editor/tagging) on the rows as **Expanded** or **Collapsed**, or hides them.
* **Graph**: Chooses whether the [Graph Editor](/docs/editor/animate-mode/graph-editor) plots **Value** or **Speed**. See [Speed Graph](/docs/editor/animate-mode/speed-graph).
## Navigating the timeline
* **Scroll and zoom**: Drag the bar at the top of the timeline to scroll. Drag its ends to zoom in or out.
* **Pan**: Right-click and drag, or hold Space and drag.
* **Maximize**: Click the maximize button on the timeline tabs to give the timeline more room. Click it again to restore the layout.
# Audio Assets
Source: https://rive.app/docs/editor/assets/audio
Import, clip, and configure audio assets in Rive.
## Importing audio
See [Importing Assets](/docs/editor/fundamentals/assets-overview#importing-assets) for information about importing files, including MP3, WAV, and FLAC files.
### Browse sounds
Browse Sounds gives you direct access to a free library of over 3,000 sounds from Soundly.
**Step 1**
In the Assets panel, click **+** and select **Browse Sounds**.
**Step 2**
In the Sounds panel, search or browse for a sound.
**Step 3**
Preview the sound, then click **+** to add it to the Assets panel.
After adding a sound to the Assets panel, you can use it in an [Audio Event](/docs/editor/events/audio-events) or reference it from a [script](/docs/scripting/getting-started).
## Export options
Audio assets include a **Source** option that controls the audio format used for export.
* **Source**: Use the original imported audio format.
* **WAV**: Export the audio as WAV.
* **FLAC**: Export the audio as FLAC.
* **MP3**: Export the audio as MP3.
## Previewing sounds
You can create a shorter clip from any audio asset.
**Step 1**
Open the **Audio** panel in the **Debug Panel**.
**Step 2**
Select an audio asset in the **Assets** panel.
**Step 3**
Click the play icon.

## Creating clips
You can create a shorter clip from any audio asset.
**Step 1**
Open the **Audio** panel in the **Debug Panel**.
**Step 2**
Select an audio asset in the **Assets** panel.
**Step 3**
Drag along the waveform to select a portion of the audio and click the play button to preview.
**Step 4**
Click **+** to create a clip.
The new clip will now appear as its own audio asset under the parent audio in the sidebar.
Select a clip to change it in the Inspector:
* **Name**: The clip's name in the **Assets** panel.
* **Range**: The start and end of the clip within its source audio, in seconds.
## Setting asset volume
Select an audio asset or clip to set its **Volume** in the Inspector.
Volume is set on the asset, not on each individual use of the asset. If the same audio asset is used in multiple places, changing its volume affects all of them.

# Photoshop Files
Source: https://rive.app/docs/editor/assets/psd
Using layered Photoshop files in Rive.
[YouTube video player](https://www.youtube.com/embed/Mlo9mQBUaTE)
## Importing PSD files
Drag a PSD file into Rive or import it from the Assets panel. When you import a PSD file, Rive adds its visible image layers to the Assets panel so you can place individual layers or the full composition on an artboard.
> [!NOTE]
>
> Hidden layers in the PSD are not imported into Rive.
## Using PSD layers
You can use PSD layers individually or as a full composition.
* Drag a layer onto an artboard to place that layer.
* Drag the entire PSD onto an artboard to create a group containing all imported layers.
## Asset settings
PSD layers use the same asset settings as raster images. You can configure settings for individual layers or apply settings to all layers in the PSD.
## Export behavior
Only PSD layers used in the Rive file are included in the exported `.riv` file by default.
You can adjust export options for individual layers or for all layers in the PSD. See [Assets](/docs/editor/fundamentals/assets-overview#asset-settings) for more about export behavior.
## Reimporting PSD files
You can replace or reimport a PSD to update its layers in Rive.
> [!WARNING]
>
> Keep PSD layer names consistent when reimporting. If you rename a layer in Photoshop and reimport the PSD, Rive treats it as a new layer. Any objects using the old layer may lose their asset reference.
# SVG & Vector Assets
Source: https://rive.app/docs/editor/assets/svg
Import SVG files and convert them into editable vector artwork.
SVG is one of the easiest ways to bring existing vector artwork into Rive.
When you import an SVG, Rive converts the SVG into native Rive vector objects. After import, the artwork is no longer an SVG—it becomes editable shapes, paths, fills, strokes, and groups that behave like any artwork created directly in Rive.
## Importing SVG files
You can import SVG files or copy vector artwork from design tools like Figma and Illustrator.
For general importing steps, see [Assets overview](/docs/editor/fundamentals/assets-overview).
### Importing from Figma
You can use **Copy as SVG** and paste it directly into the Rive editor.

### Importing from Illustrator
When exporting or copying SVGs from Illustrator, use **Presentation Attributes** for styling.
* If you use **Save As**, open **SVG Options** and set **CSS Properties** to **Presentation Attributes**.
* If you use **Export As**, open **SVG Options** and set **Styling** to **Presentation Attributes**.
* If you copy and paste directly from Illustrator into Rive, Illustrator uses the **Export As SVG** options, so make sure Styling is set to **Presentation Attributes** there.
Also disable **Preserve Illustrator Editing Capabilities**. This adds extra Illustrator data that can make the SVG much larger and may include data Rive’s importer does not recognize.
## Export behavior
SVG assets only use **Automatic** export behavior.
Rive converts SVGs into native vector objects before runtime export. The original SVG file is not included in the `.riv`, and runtimes do not currently convert SVG assets at runtime.
## Unsupported features
Most SVG artwork imports without issue, but some SVG features do not have direct equivalents in Rive and are imported differently or ignored.
| SVG Feature | Import Behavior |
| - | - |
| Embedded images | Ignored. |
| Gradient transforms | Ignored. Linear and radial gradients are still supported. |
| `stroke-dasharray` | Imported as a [dashed stroke](/docs/editor/manipulating-shapes/trim-path#dash). |
| `mask` | Imported as clipping. |
| `filter` | Not supported. |
| `skew` transforms | Not supported. |
| Inherited fills and strokes (`inherit`) | Inherited colors default to white. |
> [!NOTE]
>
> If your artwork relies on unsupported SVG features, consider converting them to editable paths in your design tool before importing into Rive.
# Constraints Overview
Source: https://rive.app/docs/editor/constraints/constraints-overview
Learn how to use constraints in Rive.
[YouTube video player](https://www.youtube.com/embed/jYW0WuvEw_4)
Constraints are a way to control the properties of an object through another target object. Some constraints can set limits on these properties (and their hierarchical relationships), while others can copy properties from one object to another.
## Learn by example
## Common use cases
* Make a character's eyes follow a target.

* Ensure a character's feet stay planted on the floor while their legs automatically bend at the knees.
* Make all the wheels on a vehicle rotate together.
* Make the hands on a clock rotate.
* Copy translation, rotation, or scale from another object.
* Push an object away as one gets closer, or ensure an object always stays close to another one.
## Strength
Every constraint has a **Strength** that sets how much it applies. At 0% it has no effect, and at 100% it applies fully. Values in between blend between the object's own transform and the constrained result.
## Constraint order
When an object has more than one constraint, they apply from top to bottom in its **Constraints** section of the **Inspector**. Drag the rows to change the order.
## Turning a constraint off
Click the eye icon on a constraint's row in the **Hierarchy** to turn it off without removing it. Click it again to turn it back on.
## Types of constraints
Types of constraints in Rive:
* [IK Constraint](/docs/editor/constraints/ik-constraint)
* [Distance Constraint](/docs/editor/constraints/distance-constraint)
* [Transform Constraint](/docs/editor/constraints/transform-constraint)
* [Translation Constraint](/docs/editor/constraints/translation-constraint)
* [Scale Constraint](/docs/editor/constraints/scale-constraint)
* [Rotation Constraint](/docs/editor/constraints/rotation-constraint)
# Distance Constraint
Source: https://rive.app/docs/editor/constraints/distance-constraint
Keep an object within, beyond, or at a specific distance from another object.
## Adding a Distance Constraint
[YouTube video player](https://www.youtube.com/embed/Nvwf27EIvdw)
**1. Add a Distance Constraint**
Select an object, then add a **Distance Constraint** from the **Constraints** section of the Inspector.
**2. Choose a target**
Open the constraint's fly-out menu and select the object to use as the target.
**3. Move the target**
Move the target to see the constraint affect the constrained object. By default, the **Closer** mode keeps it within the specified distance.
> [card] [Learn by remixing](https://rive.app/community/files/28736-distance-constraint?utm_source=docs\&utm_medium=docs_link_card\&utm_campaign=docs_to_marketplace_links)
>
> Open this file on Marketplace, then click Remix to experiment in the Rive Editor.
## Properties
### Strength
**Strength** controls how much the constraint affects the object. At 0%, the constraint has no effect.
### Distance
**Distance** sets the distance used by the constraint. A red circle on the Stage represents this distance from the target.
### Mode
**Mode** determines how the constrained object can be positioned relative to the **Distance** value.
#### Closer
Keeps the constrained object within the specified distance from the target. When the target moves too far away, the object follows to stay within that distance.
#### Further
Keeps the constrained object beyond the specified distance from the target. When the target moves too close, it pushes the object away to maintain the minimum distance.
#### Exact
Keeps the constrained object exactly at the specified distance from the target. When the target moves, the object follows to maintain that distance.
# Follow Path Constraint
Source: https://rive.app/docs/editor/constraints/follow-path-constraint
The Follow Path Constraint makes complex motion much easier to create by allowing us to constrain an object to a path.
> [!NOTE]
>
> For text that follows a path, use the [Follow Path Text Modifier](/docs/editor/text/text-modifiers#follow-path) property instead.
[YouTube video player](https://www.youtube.com/embed/9Gp_Kz-ylT4)
## Setting up a Follow Path constraint
First we’ll need both an object to constrain and a path to constrain it to.
Next, add a new constraint and select the Follow Path Constraint.

Now, use the target button and select the path you want to constrain the object to.
## Follow Path properties
Like other Constraints, the Follow Path Constraint has many different properties we can customize.
#### Strength
The strength property dictates how strictly the constrained object will adhere to the constrained property.
#### Target
The Target tells the constraint which path to follow.
#### Distance
The Distance property moves the object up and down the path. As the percent increases, the constrained object moves along the path. Note that this property can exceed 100%.

#### Orient
The Orient toggle controls the constrained objects rotation.
When the Orient toggle is on, the object will adjust its rotation according to the path. Note that you can’t make manual rotation changes to the object in this state.

When the Orient toggle is set to off, the rotation of the constrained object does not change. This means you’ll be able to manually change the rotation of the object as you see fit.
#### Offset
The Offset toggle allows the constrained object to move along the path, but from its current, offset position.
## Following a list
You can add a Follow Path Constraint to an [Artboard List](/docs/editor/data-binding/lists#artboard-lists) to spread its items along a path. Instead of a single **Distance**, the constraint has three values, each a percentage of the path:
* **Start**: Where the first list item sits.
* **End**: Where the last list item sits. The other items are spaced evenly between **Start** and **End**.
* **Offset**: Shifts every item along the path together. Animate it to move the whole list along the path.
A list with a single item places it at **Start**.
# IK Constraint
Source: https://rive.app/docs/editor/constraints/ik-constraint
Use IK constraints to control bone chains with a target.
[YouTube video player](https://www.youtube.com/embed/8FK5E5WBUpM)
## Forward vs inverse kinematics
Most skeletal animation in Rive uses **Forward Kinematics**. With Forward Kinematics, you pose a bone chain by rotating each bone. Child bones move based on the rotation of their parents.
**Inverse Kinematics** works in the opposite direction. Instead of rotating each bone manually, you place a target at the end of the chain and Rive solves the bone rotations needed to reach it.

IK is useful for rigs where the end of a chain needs to follow something else. For example, you might use IK to make a character point at an object or keep a character's feet planted on the ground.
## Creating an IK Constraint
To use IK, you need a bone chain and a target. The target can be any object, though in most cases you'll want to use a group with its [Style set to Target](/docs/editor/fundamentals/groups#target-style).
**1. Create a bone chain and a target**
Use the **B** shortcut to create a [bone chain](/docs/editor/manipulating-shapes/bones#how-to-create-bones).
Then use the **G** shortcut to create a [group](/docs/editor/fundamentals/groups).
With the group selected, set **Style** in the Inspector to **Target**. A target group stays selectable, even when other objects are above it. See [Targets](/docs/editor/fundamentals/groups#target-style).

**2. Add an IK constraint**
Select the last bone you want the IK constraint to affect. In the Inspector, use the **Constraints** section to add an **IK** constraint.

**3. Select a target**
Open the constraint flyout menu and use the target button to select the target group you created in step 1.

**4. Test the IK system**
Move the target group. The affected bones should rotate toward the target.

## IK properties
### Bone count
Use **Bone Count** to set how far up the bone chain the IK constraint should reach.
When the target is selected, bones affected by the IK constraint are highlighted.

### Invert direction
Use **Invert Direction** to swap the angle used to solve the IK chain.

### Strength
Use Strength to control how much the affected bones follow the target. A Strength of 0% means the target does not affect the bones.
Strength can be animated like most properties in Rive. This is useful for blending between Forward Kinematics and Inverse Kinematics, or for blending between multiple IK constraints with different targets.

### Constraints order
The order of constraints matters. If a bone has two IK constraints and both have a Strength of 100%, the lower constraint overrides the one above it.
If the constraints use lower Strength values, Rive blends between them. Drag constraints in the Inspector to change their order.

## Multiple IK Constraints and nested targets
You can use multiple IK constraints to create more complex rigs.
For example, a character leg might use one IK constraint on the foot and another IK constraint on the leg bones. The leg target can be a child of the foot target, so moving the foot target also moves the leg target.

# Rotation Constraint
Source: https://rive.app/docs/editor/constraints/rotation-constraint
The Rotation Constraint allows you to set limits on an object's rotation and/or copy the rotation properties from a target object. These properties can be independently activated.
[YouTube video player](https://www.youtube.com/embed/YrQeUrzYoi8)
## How to create a Rotation Constraint
**1. Add a Rotation Constraint to an object**
Use the Constraints section of the Inspector to add a Rotation Constraint to an object.

**2. Choose a target**
Use the new constraint's fly-out menu to select a target for this constraint.

**3. Test that the Rotation Constraint is working**
Manipulating the target object now causes the constrained object to copy Rotation properties.

## Strength
The Strength property determines how much the constrained object is affected.
A Strength of 0% means the constraint won't have any effect.
A Strength of 50% means half the value from the target will be applied.
## Transform Space
### Source Space
Choose whether this constraint should use World or Local coordinates for the Source Space.
### Destination Space
Choose whether this constraint should use World or Local coordinates for the Destination Space.
### Min/max space
Choose whether this constraint should use World or Local coordinates for the Min/Max Space.
## Offset
Allows the constraint owner to be manually offset from the constraint source.

## Copy
Define the rate at which the rotation property is copied.
## Min/max
Use the numerical values to define the minimum and maximum limits of the constraint.
# Scale Constraint
Source: https://rive.app/docs/editor/constraints/scale-constraint
The Scale Constraint allows you to set limits on an object's scale and/or copy the scale properties from a target object. These properties can be independently activated.
[YouTube video player](https://www.youtube.com/embed/4fFuGQHAiIQ)
## How to create a Scale Constraint
**1. Add a Scale Constraint to an object**
Use the Constraints section of the Inspector to add a Scale Constraint to an object.

**2. Choose a target**

Use the new constraint's fly-out menu to select a target for this constraint.

**3. Test that the Scale Constraint is working**
Manipulating the target object now causes the constrained object to Scale properties.
## Strength
The Strength property determines how much the constrained object is affected.
A Strength of 0% means the constraint won't have any effect.
A Strength of 50% means half the value from the target will be applied.
## Transform Space
### Source Space
Choose whether this constraint should use World or Local coordinates for the Source Space.
### Destination Space
Choose whether this constraint should use World or Local coordinates for the Destination Space.
### Min/max space
Choose whether this constraint should use World or Local coordinates for the Min/Max Space.
# Scroll Constraints
Source: https://rive.app/docs/editor/constraints/scroll-constraint
Make Layout content scrollable, scroll Data Binding lists, and add draggable scroll bars.
Scrolling in Rive is built from two constraints that work with [Layouts](/docs/editor/layouts/layouts-overview):
* **Scroll** makes the content of a Layout scrollable when it overflows its parent.
* **Scroll Bar Thumb** turns a Layout into a draggable scroll bar thumb that stays in sync with a scrolling Layout.
You can drive scrolling by dragging, with a mouse wheel or trackpad, or from an animation or [Data Binding](/docs/editor/data-binding/overview).
## Making content scrollable
A scroll region needs three levels of Layouts:
* **Scroll view**: The Layout that defines the visible scroll area.
* **Scroll content**: A Layout inside the scroll view that holds everything that scrolls. Add the Scroll constraint to this Layout. Its size sets how far the content can scroll, so set it to hug its contents or to a fixed size larger than the scroll view.
* **Scroll items**: The Layouts inside the scroll content.

**Step 1**
Select the scroll content Layout.
**Step 2**
In the **Constraints** section of the Inspector, click **+** and select **Scroll**.

**Step 3**
Click the options button on the constraint to open **Scroll Constraint** and set its properties.

**Step 4**
Switch to Animate mode and play a State Machine to test the scrolling. Drag inside the scroll view, or use a mouse wheel or trackpad.
## Scroll constraint properties
### Direction
* **Vertical** scrolls up and down only.
* **Horizontal** scrolls left and right only.
* **All** scrolls in both directions.
### Interaction
* **Interactive** lets the viewer scroll the content by dragging. Turn it off to scroll only from an animation or Data Binding. It's on by default.
* **Wheel / Trackpad** also lets the viewer scroll with a mouse wheel or trackpad. Turn it off to make the scroll view drag-only. It's on by default and has no effect when **Interactive** is off.
* **Threshold** is how far, in units, the pointer must move before a drag starts scrolling. Raise it so that taps on scroll items aren't mistaken for drags.
* **Drag Multiplier** scales how far the content moves for each drag or wheel movement. The default is 1.
When scroll views are nested, such as a horizontal strip inside a vertical list, each wheel or trackpad gesture scrolls the view that matches its direction. A flick that starts in the inner view keeps scrolling the inner view instead of passing to the outer one.
### Scroll position
* **Scroll Percent X** and **Scroll Percent Y** set the scroll position as a percentage, where 0% is the top or left and 100% is the bottom or right. Each appears only when the direction allows scrolling on that axis.
* **Scroll Index** scrolls to an item by its zero-based index. It appears only when the direction is **Vertical** or **Horizontal**.
You can key these properties on the timeline or bind them to View Model properties.
> [!WARNING]
>
> Scroll Percent and Scroll Index both set the same scroll offset. Use only one at a time. For example, don't key both on the same frame.
> [!TIP]
>
> To combine keyed scroll positions with dragging, transition to an empty "reset" state as soon as the viewer interacts with the scroll view, for example with a **Pointer Down** listener on the scroll view. Otherwise the keyed value overrides the drag.
### Physics
* **Elastic** decelerates after a flick and rubber-bands at the edges, like scrolling on iOS. Set how it feels with:
* **Friction**: How quickly scrolling slows down after a flick.
* **Speed Multiplier**: How fast a flick scrolls.
* **Elastic Factor**: How far the content stretches past the edges.
* **Clamped** moves the content with the pointer and stops at the edges, with no momentum.
### Snap
When **Snap** is on, the content always comes to rest with an item aligned to the top or left of the scroll view. It's off by default.
### Read-only scroll state
These properties report what the scroll view is doing. You can't edit them, but you can bind them to View Model properties to react to scrolling, for example to show a "back to top" button or fade a header:
* **Scroll Active** is true while the content is being dragged or is still moving.
* **Velocity X** and **Velocity Y** report the current scroll speed on each axis.
## Scrolling a list
To scroll a [Data Binding list](/docs/editor/data-binding/lists), use the same setup as above, but put a single list inside the scroll content instead of separate scroll items.
These extra properties turn on once the scroll content contains a list:
* **Virtualize** creates components only for the items that are visible, instead of for every item in the list. Turn it on for long lists to improve performance. **Buffer** keeps the given number of extra items ready on each side of the visible area, so they're already running when they scroll into view. Stack layouts can't be virtualized. A grid can be virtualized only if every child of the scroll content is a list.
* **Carousel** makes the list loop endlessly in both directions. Turning on **Carousel** also turns on **Virtualize**.
## Adding a scroll bar
A scroll bar needs two Layouts:
* **Scroll bar**: The Layout that defines the track.
* **Scroll thumb**: The Layout inside the track that the viewer drags.

**Step 1**
Select the scroll thumb Layout.
**Step 2**
In the **Constraints** section of the Inspector, click **+** and select **Scroll Bar Thumb**.

**Step 3**
Open the constraint's options. Use the target button to select the scroll content Layout, which is the Layout with the Scroll constraint.

The **Scroll Thumb Constraint** options also include:
* **Direction**: The axis the thumb moves along.
* **Auto Size**: Resizes the thumb to show how much of the content is visible, like a browser scroll bar. When it's off, the thumb keeps the size you set.
# Transform Constraint
Source: https://rive.app/docs/editor/constraints/transform-constraint
The Transform Constraint allows its owner to copy all the transformation properties from a target object, regardless of their hierarchical relationships. These properties include Position, Rotation, and Scale.
[YouTube video player](https://www.youtube.com/embed/pJfWNtVBrvM)
## How to create a Transform Constraint
**1. Add a Transform Constraint to an object**
Use the Constraints section of the Inspector to add a Transform Constraint to an object.

**2. Choose a target**
Use the new constraint's fly-out menu to select a target for this constraint.

**3. Test that the Transform Constraint is working**
Manipulating the target object now causes the constrained object to copy Position, Rotation, and Scale properties.

## Strength
The Strength property determines how much the constrained object is affected.
A Strength of 0% means the constraint won't have any effect.
A Strength of 50% means half the value from the target will be applied.

## Origin
**Origin X** and **Origin Y** set the pivot used when copying the target's transform, as a percentage of the target's size. For Origin X, 0% is the left edge, 50% the center, and 100% the right edge. For Origin Y, 0% is the top, 50% the center, and 100% the bottom.
## Transform Space
### Source Space
Choose whether this constraint should use World or Local coordinates for the Source Space.
### Destination Space
Choose whether this constraint should use World or Local coordinates for the Destination Space.
# Translation Constraint
Source: https://rive.app/docs/editor/constraints/translation-constraint
The Translation Constraint allows you to set limits on an object's position and/or copy the position properties from a target object. These properties can be independently activated.
[YouTube video player](https://www.youtube.com/embed/i6OAPcqcPBw)
## How to create a Translation Constraint
**1. Add a Translation Constraint to an object**
Use the Constraints section of the Inspector to add a Translation Constraint to an object.

**2. Choose a target**
Use the new constraint's fly-out menu to select a target for this constraint.

**3. Test that the Translation Constraint is working**
Manipulating the target object now causes the constrained object to copy Position properties.

## Strength
The Strength property determines how much the constrained object is affected.
A Strength of 0% means the constraint won't have any effect.
A Strength of 50% means half the value from the target will be applied.
## Transform Space
### Source Space
Choose whether this constraint should use World or Local coordinates for the Source Space.
### Destination Space
Choose whether this constraint should use World or Local coordinates for the Destination Space.
### Min/max space
Choose whether this constraint should use World or Local coordinates for the Min/Max Space.
## Offset
Allows the constraint owner to be manually offset from the constraint source.

## Copy X \&Y
Allows you to decide if the constraint owner will copy the translation in the X and Y direction. Additionally, use the numerical value to define the rate at which it copies the value.
## Max/min
Use the numerical values to define the minimum and maximum limits of the constraint.
# Binding Data
Source: https://rive.app/docs/editor/data-binding/binding-data
Binding is how you connect data to properties and elements in your Rive file.
For example, if you have a `teamName` property bound to a text run in your scene, changing the `teamName` value updates the displayed text automatically.
You can change property values in the editor or at runtime, allowing you to create dynamic experiences that adapt to each user.
Bindings are not limited to visual properties. You can bind values throughout your file, including transforms, animation speeds, [converter values](/docs/editor/data-binding/converters#converter-types), [script inputs](/docs/scripting/script-inputs#data-binding-inputs), [transition condition values](/docs/editor/state-machine/transitions), and more.
This allows the same data to drive behavior, animation, and logic across your scene, helping keep everything in sync.
## Binding a property
Let's control the `X` position of a circle using `circleX`, which is a Number property in our View Model.

**1. Bind the property**
With your circle selected, right-click the `X` field, and select **Data Bind**.
**2. Select the property**
In the **Property** dropdown, select `circleX`.
The `X` field should now be highlighted in green, indicating that it's bound to a value.
The circle's horizontal position is now driven by the `circleX` property. Any time the property's value changes, the circle updates automatically.

> [!WARNING]
>
> If the field has a yellow border, there is a problem with the binding.
>
> In most cases, the property type is incompatible with the target value. For example, the `X` position of an element can only be bound to a Number property.
> [!TIP]
>
> **Previewing Bindings**
>
> By default, your data only controls your elements when the state machine is playing.
>
> To preview your data-bound values, turn on the **Data Binding Preview Toggle**.
>
> 
### Creating a property while binding
You can create a new View Model property from the bind popup instead of adding it in the Data panel first.
**1. Open the New Property form**
Right-click the field, select **Data Bind**, then click the **New Property** (**+**) icon in the popup's header.
**2. Choose a View Model**
In **Model**, select the View Model to add the property to. To make a new View Model, select **Create New** and enter a name that doesn't match an existing View Model.
**3. Name the property**
Enter a name in **Property**. Its type matches the field you're binding.
**4. Set a starting value**
**Value** sets the property's starting value on every instance. It defaults to the field's current value.
**5. Create it**
Click **Create Property** or press `Enter`. Rive creates the property and binds the field to it.
> [!NOTE]
>
> Only String, Number, Boolean, Color, and Trigger properties can be created here. For other types, such as lists, enums, and assets, create the property in the Data panel.
### Updating a binding
Right-click the bound element and select **Update Bind**.

### Removing a binding
Right-click the bound element and select **Unbind**.

### Finding bound objects
In the **Hierarchy**, objects with bound properties show a data bound badge. The arrows show which way data flows, and the badge turns amber when a binding is invalid. Hover the badge to see the bound properties.
If an object has no bindings of its own but something inside it does, it also shows a badge. Expand it to find the bound object.
## Binding options
Each binding has the following properties.
### Property
The View Model property the target is connected to.

> [!NOTE]
>
> When binding global properties, select the **Globals** icon.
>
> 
### Path
When binding properties in nested View Models, there may be multiple properties with the same name available.
The path determines which specific property instance the binding should use.

See also [Absolute vs Relative Binding](#absolute-vs-relative-binding).
### Bind direction
By default, the View Model property (**source**) controls the bound element or value (**target**), but it can also work the other way around.
[YouTube video player](https://www.youtube.com/embed/Syt6i4-Bkm4)
#### Target to source
When a binding has `Target to Source` toggled on, a change to the element will update the view model property.

Tip
**Example - Tracking Positions**
Let's say you have a walk cycle animation and you want to track the exact Y position of the head as it bobs up and down.
With the head's `Y` position bound to `headY` using **Target to Source**, the `headY` property updates automatically as the head moves.
#### Bidirectional
A change to the view model property will update the element **AND** a change to the element will update the view model property.

Clicking the **Bidirectional** toggle multiple times will cycle between **Bidirectional (prefer target value)** and **Bidirectional (prefer source value)**.
In rare cases, both the source and target may change at the same time. This setting determines which value wins when a conflict occurs.
Tip
**Example - Checkers**
Let's say you're building a game of checkers and need to create logic for dragging and dropping each piece.
The initial position of each piece is determined by the `piecePositionX` and `piecePositionY` properties (source to target).
As the piece is dragged, the piece itself (target) updates those property values (target to source).
### Bind once
When **Bind Once** is enabled, the binding only applies the value a single time when the scene starts or the binding is created.

After the initial value is applied, future changes to the source or target are ignored.
Tip
**Example**
Let's say you're creating a particle effect and want each particle to start with a random rotation value.
You could bind the particle's rotation to a random number property using **Bind Once**. Each particle would receive its initial rotation value, but future changes to the property would not affect existing particles.
### Absolute vs relative binding
[YouTube video player](https://www.youtube.com/embed/4LOXhXesG74)
By default, new data binding connections are created as absolute binds.
* **Absolute Binding** points to a specific property instance within the View Model hierarchy.
* **Relative Binding** searches for a property with a matching name, starting with the closest View Model and working up the hierarchy.
Because relative bindings resolve by name, a closer property with the same name can take precedence over the property you intended to bind. For example, if a binding targets a property named `scale` in the main View Model, but a closer View Model also contains a property named `scale`, the binding will resolve to the closer property.
> [!NOTE]
>
> Bindings to [Global View Models](/docs/editor/data-binding/view-models#global-view-model-instances) are always relative.
# Controlling Data
Source: https://rive.app/docs/editor/data-binding/controlling-data
Update and react to data from within Rive or from your application code.
Once you've bound data to properties in your file, changing that data will automatically update the connected elements.
You can control data from within your Rive file, or from your application at runtime.
## Controlling data within Rive
Rive includes several ways to update data directly inside your file:
> [card] [State machine actions](/docs/editor/state-machine/actions)
>
> Update property values when [transitions](/docs/editor/state-machine/transitions#actions) or [state changes](/docs/editor/state-machine/states#actions) occur.
> [card] [Listener actions](/docs/editor/state-machine/listeners)
>
> Update data in response to interactions and events.
> [card] [Scripting](/docs/scripting/data-binding)
>
> Write custom logic that reads and updates data.
> [card] [Target-to-source Binding](/docs/editor/data-binding/overview#bind-direction)
>
> Update data using an element's property value.
> [card] [Property Groups](/docs/editor/data-binding/property-groups)
>
> Animate values and bind them back to data.
## Controlling data from code
Your application can also update data at runtime. For example, you might:
* Update a player's score
* Change a username or profile image
* Display live stock prices
* Trigger UI states based on user interaction
See the [Runtime Data Binding Overview](/docs/runtimes/data-binding) for implementation details.
# Converters
Source: https://rive.app/docs/editor/data-binding/converters
Transform and adapt data before it’s applied to a binding using built-in and custom converters.
[YouTube video player](https://www.youtube.com/embed/td59TXa_xQI)
Converters transform values before they are applied to a binding.
Use them to adapt your data to match the property you're binding to—for example, converting numbers to strings, mapping values between ranges, or smoothing changes over time.
## Adding a Converter

**1. Create a Converter**
In the Assets panel, click the `+` button and select a [converter type](#converter-types).
**2. Set Converter Options**
With the converter selected, update the settings in the right sidebar.
> [!NOTE]
>
> Most options can be data bound.
**3. Apply your Converter**
When setting or updating a binding, set the **Converter** field.
## Converter types
Converters can be used individually or combined into [groups](#converter-groups) to perform more complex transformations.
Each converter has its own set of properties, many of which can be bound to other View Model properties.
This allows converter behavior to update dynamically. For example, you could bind the maximum value of a range map, a multiplier in a formula, or the padding amount in a string converter.
A bind on a converter's property can use a converter of its own, nested as deep as you need. Choose it in the **Convert** row of the data binding popup, the same as for any other bind. For example, a Formula can read an enum through **Convert to Number**, so a value like "visible when skin A or skin B is on" comes straight from a View Model.
| Category | Converter | Description |
| - | - | - |
| String | [Pad](#pad) | Add padding to a string |
| | Trim | Remove leading or trailing whitespace |
| | [Convert to String](#convert-to-string) | Convert a value to a string |
| | Remove Trailing Zeros | Remove unnecessary decimal zeros |
| | [String Template](/docs/editor/data-binding/string-template) | Build text from a template and view model values |
| Number | Round | Round to the nearest value |
| | Calculate | Perform simple calculations |
| | [Range Map](#range-map) | Map a value from one range to another |
| | [Interpolator](#numeric-interpolator) | Smoothly interpolate between values |
| | [Formula](#formula) | Evaluate a custom expression |
| | Convert to Number | Convert a value to a number |
| Boolean | Toggle | Invert a boolean value |
| List | [Number to List](#number-to-list) | Generate a list of components based on a number |
| | [List to Length](#list-to-length) | Get the number of items in a list |
| Color | [Interpolator](#color-interpolator) | Smoothly interpolate between colors |
| Script | [Converter Scripts](#converter-scripts) | Create your own custom converters |
### Pad
Pads a string to a target length by repeating a value at the start or end.
If the string is shorter than the specified length, the pad value is repeated and added until the target length is reached.
**Example:**
* **Value:** 1
* **Pad:** "0"
* **Direction:** Start
* **Length:** 3
**Result**: "001"
***
### Convert to string
Converts a number, color, enum, or boolean into a string. Enums become the name of their value, and booleans become `1` or `0`.
**From a Number**
* **Round Decimals**: Round to the number of decimal places you set.
* **Remove Trailing Zeros**: Drop zeros at the end of the decimals, such as `2.50` to `2.5`.
* **Format With Commas**: Add thousands separators, such as `1,234,567`.
**From a Color**
Use **Format** to choose how a color is written. Each code is replaced with one channel of the color, and any other text is kept as is. Click **+** next to **From a Color** to insert a code.
| Code | Channel |
| - | - |
| `%r` `%g` `%b` `%a` | Red, green, blue, or alpha, from 0 to 255 |
| `%R` `%G` `%B` `%A` | Red, green, blue, or alpha, as two-digit hex |
| `%h` | Hue, from 0 to 360 |
| `%s` | Saturation, from 0 to 100 |
| `%l` | Luminance, from 0 to 100 |
To show a `%` as literal text, put a backslash before it: `\%`.
**Example:**
* **Format:** `#%R%G%B`
* **Value:** orange
**Result**: "#FF8800"
***
### String template
Builds text by filling placeholders in a template with view model values. See [String Template Converter](/docs/editor/data-binding/string-template).
***
### Range map
Maps a number from one range to another.
Use Range Map when you want to take an input value and convert it into a different scale.
**Example**
Convert a slider value (0–100) into an opacity value (0–1):
* **Input**: 50
* **Input range**: 0 → 100
* **Output range**: 0 → 1
**Result**:
0.5
**Options**
* **Clamp**: Click the clamp buttons next to the output range to keep the result from going below the lower bound or above the upper bound.
* **Interpolation**: Choose **Linear**, **Cubic**, or **Elastic** to control how values are mapped between the two ranges.
* **Reverse**: Reverse the mapping.
* **Modulo**: Wrap the value when it goes past the range.
Use the presets menu next to the output range to set common ranges, such as 0–1, 0–100, or 0–360 degrees.
***
### Numeric interpolator

Smoothly transitions between number values over time, easing changes instead of jumping instantly.
***
### Formula

Formula lets you perform custom calculations using values from your View Model or the input.
You can create a formula in two ways:
**Writing it directly**
```lua theme={null}
random({{NumberConvertersVM/circleX}} / {Input}) + 2
```
> [!NOTE]
>
> `{Input}` refers to the incoming value, while `{{...}}` references View Model properties.
**Using the editor**
Click the + button to add values, operations, and functions. This builds the formula for you and generates the equivalent expression.
> [!TIP]
>
> **Formulas don't need inputs**
>
> The following formula would output a random number, regardless of input.
>
> ```lua theme={null}
> random(2)
> ```
#### Random mode
When using `random()` in your formula, the Random Mode determines when a new random value is generated.
* **Once** — Generates a random value only when the formula first runs
* **Source Change** — Generates a new value each time the input changes
* **Always** — Continuously generates new values while the input changes and during interpolation
***
### Number to list
The Number to List converter allows you to generate a specified number of Components based on a number.
See [Lists](/docs/editor/data-binding/lists#view-model-number-with-converter) for more information.
***
### List to length
Converts a list into a number: the number of items in the list.
Use it to show an item count, or to drive other properties or conditions from the size of a list.
***
### Color interpolator

Smoothly transitions between color values over time, easing changes instead of jumping instantly.
***
### Converter Scripts
Scripting lets you create your own custom converters when you need behavior that isn’t covered by the built-in converters.
See [Converter Scripts](/docs/scripting/protocols/converter-scripts) for more information.
## Converter groups

Converter groups let you chain multiple converters together, where the output of one becomes the input of the next.
**1. Create a Converter Group**
In the Assets panel, click the `+` button and select Converter > Group.
**2. Add a Converter to Your Group**
With the group selected, add the `+` button in the right sidebar and select an existing or new converter.
When binding a value, your converter group can now be used just like an individual converter.
### How execution works
Converters run from top to bottom:
* The first converter receives the original input
* Each converter passes its result to the next
* The final output is the result of the last converter
### Reordering converters
Drag a converter up or down to change when it runs.
Earlier converters affect all converters that follow.
# Enums
Source: https://rive.app/docs/editor/data-binding/enums
Use enums to control states, modes, and variants by selecting from a predefined set of options.
[YouTube video player](https://www.youtube.com/embed/DgDBjxWl8Aw)
An enum lets you choose one value from a predefined set of options.
Use enums when a property should only ever be one of a few known values—like modes, states, or variants—instead of allowing any arbitrary value like a string.
For example, instead of using a string like "left", "center", or "right", an enum guarantees the value is always one of those valid options.

Enums can be:
* System enums — built-in sets of options used by the editor (for example, Horizontal Align)
* [Custom enums](#custom-enums) — your own defined sets of options for your specific use case
> [card] [Learn by remixing](https://rive.app/community/files/27312-control-editor-properties-with-enums?utm_source=docs\&utm_medium=docs_link_card\&utm_campaign=docs_to_marketplace_links)
>
> Open this file on Marketplace, then click Remix to experiment in the Rive Editor.
> [!NOTE]
>
> **Why not use strings or numbers?**
>
> Imagine a calendar app that shows different backgrounds based on the day of the week.
>
> You could use a string like "Monday", but it breaks if someone sets it to "Mon".
>
> You could use a number, but it’s unclear whether the week starts on Sunday or Monday—or whether the index starts at 0 or 1.
>
> With an enum, the value must be one of the defined options, so it’s always valid and unambiguous.
## Adding an enum property

**1. Create a new enum property**
Create a new enum view model property inside your view model.
**2. Set the enum type**
Click the dropdown next to the property name and select an enum type.
**3. Set the default enum value**
Select your enum view model property and in the right sidebar, select the default value.
## Binding enums

Enums can be bound to editor properties that use the same set of options. For example, an enum named “Layout Direction” can be bound to a layout’s Direction property.
When binding enums, the System Enum to Uint converter is required and is applied automatically.
## Custom enums

**1. Create a new enum**
Open the Data panel, click the `+` icon and select enum.
**2. Add enum options**
With your enum selected, click the `+` icon in the right sidebar.
**3. Assign the enum to a property**
Assign your custom enum to your enum view model property.
## Controlling Solos with enums
Use an enum to control which Solo is active by mapping each enum value to a Solo.

**1. Create a matching enum**
Create a [custom enum](#custom-enums) with values that match the **names and order** of your Solos.
**2. Export names**
[Export the names](/docs/editor/exporting/exporting-names) of the objects used by the Solo so they are accessible at runtime.
**3. Bind the enum**
Bind the enum to the Solo’s **Active** property and apply a **Convert to Number** converter.
# Lists
Source: https://rive.app/docs/editor/data-binding/lists
Use Data Binding to generate lists at runtime
[YouTube video player](https://www.youtube.com/embed/VCWcOtUfIc8)
A List is a way to display a set of items that are dynamically generated based on bound data values that you set up in your View Models. This allows you to build Rive files that can change in real time based on updates to those values. You can use Lists to create:
* Menus with a dynamic amount of options
* Product listings
* Notifications or activity feeds
* Chat messages
* Dropdown menus
* Contacts, friends, or followers lists
* High scores, tables, and more
***
## Artboard lists
Artboard Lists enable you to generate a number of list items using an Artboard to represent each item in your List. Artboard Lists must be added as children of an Artboard or Layout.
To add an Artboard List to the stage, first select either an Artboard or a Layout. In the inspector on the right side of the editor, you will see a button to add an Artboard List. Click it to add the List to your hierarchy. It will appear as a child of the Artboard or Layout you had previously selected.

Once the Artboard List is added to your hierarchy, you can select it and see its inspector.

The next step is to bind data to it using Data Binding. This will determine the content and number of items in your List. There are 2 ways to generate List content:
* Using the View Model List property
* Using a View Model Number property together with a Number to List converter
### View Model mapping
By default, each list item is drawn with the Artboard its View Model is bound to. To use a different Artboard, select the Artboard List and click `+` in the **View Model mapping** section of the inspector. Then choose a View Model and the Artboard that should draw list items of that type.
## View Model list property
> [!NOTE]
>
> Before continuing, it's important to understand the fundamentals of Data Binding, in particular, what a View Model is, how to create one and how to bind it to an object's properties. Learn more in the [Data Binding Overview](/docs/editor/data-binding/overview).
A View Model List is a property that can contain a dynamic number of items which each represent a View Model instance. In order to be used in a List, the View Model must be bound to an Artboard.
To Create a View Model List and bind it to an Artboard List:
**1. Create a List Item View Model**
Navigate to the Data tab in the Editor. Click the + button beside View Models to create a View Model (this will represent your List item)
**2. Bind the List Item View Model to your Item Artboard**
Bind that View Model to an Artboard that you want to use to render your List item. This is where you may also want to create additional View Model properties and bind those to object properties on that Artboard.
**3. Create your Main View Model**
Click the + button beside View Models to create another View Model (this will be the View Model that contains your List and should be bound to the Artboard where you want your List to render)
**4. Add a List property**
Select the newly created View Model and click the + button next to it. From the popout select **List**. This adds a List property to the View Model 
**5. Add List Items**
Select the List property and in the inspector on the right, you can add items by clicking Add List item  Once a List item is added, you can click the settings button to the left of its name in order to set the View Model and View Model instance for that item
**6. Bind the List property to your Artboard List**
After adding your List items, go back to the Hierarchy tab, select the Artboard List, and from the Artboard List property dropdown, select the ViewModel List property you created above.
To remove the binding, click the delete button next to the Artboard List property dropdown.
Run the state machine and you should see your list items. Remember that the layout will be determined by the Artboard List's parent, so modify the parent's settings in order to tweak your List's layout
> [!NOTE]
>
> Rive's runtimes provide [APIs to modify the List and List items at runtime](/docs/runtimes/data-binding#lists) (for example, adding or removing items).
## View Model number with Converter
The second way to populate your list is by specifying the number of items you want in your List along with the ViewModel (Artboard) you want to instance. This can be done using a View Model Number property in combination with the new Number to List converter.
To Create a View Model Number to List converter and bind it to an Artboard List:
**1. Create a List Item View Model**
Navigate to the Data tab in the Editor. Click the + button beside View Models to create a View Model (this will represent your List item)
**2. Bind the List Item View Model to your Item Artboard**
Bind that View Model to an Artboard that you want to use to render your List item. This is where you may also want to create additional View Model properties and bind those to object properties on that Artboard.
**3. Create your Main View Model**
Click the + button beside View Models to create another View Model (this will be the View Model that contains your Number property and should be bound to the Artboard where you want your List to render)
**4. Add a Number property**
Select the newly created View Model and click the + button next to it. From the popout select Number. Select the newly created Number and in the inspector, set the number of items you want in your List
**5. Add a Number to List converter**
Click the + button and choose **Converters > List > Number to List**. 
**6. Set the View Model to use in the converter**
Select the created converter and in the inspector, choose the View Model that you created earlier that represents your List item. The converter will convert the Number of items to actual Artboard items 
**7. Bind the Number property and converter to your Artboard List**
After adding your Number property and converter, go back to the Hierarchy tab, select the Artboard List, and from the Artboard List property dropdown, select the ViewModel Number property you created above. The Combobox will show a yellow outline. Right click the Combobox and choose Update Bind. In the converter field, select the Number to List converter you created. The yellow outline should change to green.
Run the state machine and you should see your list items. Remember that the layout will be determined by the Artboard List's parent, so modify the parent's settings in order to tweak your List's layout
## List attributes
List attributes are special View Model properties that connect a list item to its List. To add one, click the `+` button next to your item's View Model and select **List Attributes**.
The **General** group contains attributes any list item can use:
* [**Index**](#view-model-list-item-index): the item's position in its parent List.
* [**Draw Index**](#view-model-list-item-draw-index): a number that sets the item's draw order.
The **Text** group contains attributes for [text lists](#text-list-attributes).
### Text list attributes
A text can build its runs from a list. Select the text, then use **Bind** in the **Text Runs** section of the Inspector to bind a View Model List property. Each list item becomes a text run.
Add these attributes to the item's View Model from **List Attributes > Text** to set each run's text and style:
* **Text Content**: a String that sets the run's text.
* **Text Style**: a String naming one of the text's styles to apply to the run. If no style has that name, the run uses the first style.
> [!TIP]
>
> In the Data panel, click **+** and select **View Model > Templates > Text Run** to create a View Model that already has both attributes.
## View Model list item index
There may be times where it is useful for the Artboard to know at which index it exists within its parent List. This is available using the View Model list item index property.
[YouTube video player](https://www.youtube.com/embed/CHXIOKQOq6Y)
This can be added to your item's View Model by clicking the + button and selecting **List Attributes > General > Index**.

This property can then be bound to an object's properties and used directly (for example, to change the position of an object based on the index), used together with a converter (to display the index value as a string) or used as a condition in a state machine (to provide different behavior depending on the item's index).
> [!NOTE]
>
> When using item index with the [List property](/docs/editor/data-binding/lists#view-model-list-property) and list items, be aware that if more than 1 list item is bound to the same View Model instance, they will share the same index value
## View Model list item draw index
By default, a List draws its items in list order. To control the draw order yourself, add a draw index to your item's View Model by clicking the + button and selecting **List Attributes > General > Draw Index**.
Draw Index is a Number property. When your item's View Model has one, the List draws its items in ascending draw index order instead of list order. Bind or change the value to bring items in front of or behind each other.
## Lists & scrolling
If you add your Artboard List as a child of a Layout, your List items will behave as children of its parent's Layout. This means things like direction, wrapping, padding, gap, alignment, etc. are all dictated by the parent Layout's properties.
In addition, if you have applied a [Scroll Constraint](/docs/editor/constraints/scroll-constraint) to the parent Layout, the List items will have the ability to scroll out of the box without any additional setup.
There are additional Scroll properties that can be applied when scrolling Lists. See [List Scrolling](/docs/editor/constraints/scroll-constraint#scrolling-a-list) for more details.
# Migration Guide
Source: https://rive.app/docs/editor/data-binding/migration-guide
Migrate from State Machine Inputs and Listening to Events at runtime to Data Binding
Data binding replaces both **state machine inputs** and **runtime event listeners**, and also removes the need to directly modify elements like text runs from code.
It provides more data types in a more flexible, consistent system for both sending data into Rive and reacting to changes from Rive.
| | Inputs | Events | View Model Properties |
| - | :- | :- | :- |
| Floating point numbers | ✅ | ✅ | ✅ |
| Booleans | ✅ | ✅ | ✅ |
| Triggers | ✅ | ❌ | ✅ |
| Strings | ❌ | ✅ | ✅ |
| Enumerations (Enums) | ❌ | ❌ | ✅ |
| Colors | ❌ | ❌ | ✅ |
| View Model Nesting | ❌ | ❌ | ✅ |
| Lists | ❌ | ❌ | ✅ |
| Images | ❌ | ❌ | ✅ |
| Artboards | ❌ | ❌ | ✅ |
> [!NOTE]
>
> You do **not** need to update existing files. Inputs and events will continue to work as expected. Data binding is recommended for new work and future updates.
## Migrating from deprecated features
### State Machine Inputs
State machine inputs were previously the main way to control animations from code.
With data binding, you instead expose **view model properties** that can drive State machine transitions, Blend states, and Any bindable property in the editor
**Step 1**
Open the **hamburger menu** in the editor
**Step 2**
Select **Convert Inputs to View Models**
**Step 3**
Update your runtime code to set values on the view model instead of inputs
[YouTube video player](https://www.youtube.com/embed/zo7dnTkIgHA)
> [!NOTE]
>
> **Why are State Machine Inputs deprecated?**
>
> Inputs are limited to driving state machine transitions and must be used as-is.
>
> View model properties:
>
> * Can drive more than just transitions
> * Can be transformed using [Converters](/docs/editor/data-binding/converters)
> * Can be shared across multiple parts of a file
> * Provide a more flexible and scalable data model
### Communicating with code via events
Events were previously used to send information from a Rive file back to runtime code.
With data binding, you instead **listen to changes on view model properties**, including trigger and lists.
> [!NOTE]
>
> **Why is listening for Events at runtime deprecated?**
>
> Events had several limitations:
>
> * Difficult to pass dynamic or changing data
> * Required manual handling to work across nested artboards
> * Represented a one-time signal rather than a persistent value
>
> View model properties always reflect the latest value and can be observed directly.
Instead of listening for an event:
* Create a **view model property**
* Update it from your Rive file (via animation, listener, or script)
* Subscribe to that property in your runtime
For more info, see [Data Binding](/docs/runtimes/data-binding)
***
### Updating Text Runs at runtime
Previously, updating text required:
* Knowing the exact **name**
* Knowing the **hierarchy/path**
* Accessing the text run directly from code
This approach was brittle and easy to break when files changed.
With data binding:
* Bind a **string property** to a text run
* Update the value through the view model
This keeps your runtime code stable even if the structure of your file changes.
## Constraints vs Data Binding
Constraints are still fully supported and remain the best option for many use cases.
### When to use constraints
Use constraints when:
* You are linking one object directly to another
* The relationship is purely visual or spatial
* You want a simple, editor-only solution
### When to use Data Binding instead
Use data binding when:
* The value needs to come from **runtime code**
* Multiple elements depend on the same value
* You want to introduce **logic or transformation** (via [Converters](/docs/editor/data-binding/converters))
* The relationship isn’t strictly object-to-object
> [!TIP]
>
> **Example:**
>
> You could:
>
> * Use a **constraint** to link the rotation of multiple wheels together
>
> Or:
>
> * Use a **data-bound `rotation` property** that:
> * Is controlled at runtime
> * Drives all wheels
> * Can be reused elsewhere (speed, effects, UI, etc.)
Data binding is more flexible, while constraints are more direct.
# Data Binding Overview
Source: https://rive.app/docs/editor/data-binding/overview
Connect editor elements to data and code using View Models
[YouTube video player](https://www.youtube.com/embed/M6goAzrDop4)
Data binding connects data stored in View Models to properties in your Rive scene.
When data changes, your scene updates automatically. Likewise, changes made in your scene can be written back to your data.
For example, you might:
* Bind an enemy's X and Y position so it can be controlled at runtime.
* Bind the color of multiple icons to a single color property.
* Bind a `health` value to a health bar in the UI and to the character.
* Swap images, artboards, or components based on your application's state.
## Why use Data Binding?
Data binding lets you organize your data independently from your scene hierarchy.
For example, you might have a `health` property stored at the top level of your data, while the health bar that displays it is nested several layers deep inside components.
Once the property is bound, the hierarchy no longer matters. You can move elements, reorganize components, or rename properties without rewriting runtime code.
## Core concepts
1. [View Models](/docs/editor/data-binding/view-models) define the structure of your data.
2. View Model Instances store actual values for that data.
3. [Bindings](/docs/editor/data-binding/binding-data) connect View Model data to properties in your scene.
4. [Data can be updated](/docs/editor/data-binding/controlling-data) from the Editor, runtime code, state machines, or scripting.
5. Listeners, runtime code, and scripts can respond when data changes.
6. When data changes, bound elements automatically update to reflect the new values.
# Property Groups
Source: https://rive.app/docs/editor/data-binding/property-groups
Create local values that can be keyed, animated, and bound to View Model properties.
Property Groups are local, artboard-level values that can be keyed, animated, and bound to View Model properties.
View Model properties are global and shared, while timelines and state machines are local. Property Groups bridge that gap, allowing local animation and logic to read from or drive global data.
## Creating a Property Group
**1. Create a Property Group**
Select your Property Group tool and click the stage to add one to your artboard.

**2. Add a property**
Select your Property Group and in the right sidebar, click the `+` icon and select your property type.

## Common use cases
### Controlling a View Model property with a Timeline
You can’t key a View Model property directly in the timeline. Instead, you key a Property Group value, then bind that value to a View Model property.
This lets you use [Keyframes](/docs/editor/animate-mode/keys) in a timeline to update View Model data at runtime.
> [!NOTE]
>
> **Why can't I key View Model Properties directly?**
>
> View Model properties represent global data shared across your app, while keyframes are local to a timeline—so they can’t be keyed directly.
[YouTube video player](https://www.youtube.com/embed/V7GYhd8ZHYg)
> [card] [Learn by remixing](https://rive.app/community/files/27294-property-groups-demo?utm_source=docs\&utm_medium=docs_link_card\&utm_campaign=docs_to_marketplace_links)
>
> Open this file on Marketplace, then click Remix to experiment in the Rive Editor.
**1. Key a property**
With the Property Group selected, move the timeline playhead and change the property value to create keyframes.

**2. Bind the property**
Right-click the property and select the View Model property you want to control. Set the direction to Target → Source so the keyed value drives the View Model property.

When you run your state machine, the View Model property updates based on the keyed Property Group values.
### Controlling one View Model property with another
You can't directly control one View Model Property with another View Model Property. Instead, you can use a Property Group value that reads one View Model Property and sets another.
> [!NOTE]
>
> **Why can't I control one View Model property with another?**
>
> Allowing View Model properties to control each other would create hidden dependencies and update loops, so relationships between values are handled explicitly through bindings.
In this example we'll have two Number View Model Properties called `myNumber` and `myOtherNumber`, which will be `myNumber` doubled.
> [card] [Learn by remixing](https://rive.app/community/files/27294-property-groups-demo?utm_source=docs\&utm_medium=docs_link_card\&utm_campaign=docs_to_marketplace_links)
>
> Open this file on Marketplace, then click Remix to experiment in the Rive Editor.
**1. Create a Formula Converter**
Create a new Converter of type Numeric > Formula and add a number value, a multiply operation, and another number.

**2. Bind the number value**
Bind the first number to `myNumber`.

**3. Control the View Model Property**
Select the Property Group, right-click the property, and bind it to the `myOtherNumber` value using the converter. Set the direction to Target → Source so the converted value drives the View Model property.

When you run your state machine, you should see that `myOtherNumber` is double `myNumber`.

# View Model Properties
Source: https://rive.app/docs/editor/data-binding/property-types
A view model property is one piece of data within a view model. Developers might think of this as similar to a field in object-oriented programming. Properties have a data type, which is selected when they are created, and a name which can be referenced in code. Each property can be bound to different editor elements of the same type or used as conditions within a state machine.
## Adding View Model properties
In the Data panel, click the **Add View Model Property** button next to the view model name and select your property type.

| Type | Description |
| - | - |
| Number | Numeric value |
| String | Text value |
| Boolean | True/false value |
| Color | RGBA color value |
| [Trigger](#trigger) | Fire-and-forget event |
| [Enum](#enum) | One value from a predefined list |
| [Image](#image) | Image asset reference |
| [Font](#font) | Font asset reference |
| [Blob](#blob) | Blob asset reference |
| [Artboard](#artboard) | Artboard reference |
| [View Model](#view-model) | Nested View Model instance |
| [List](#list) | Collection of view models |
## Property types
### Trigger
Trigger properties represent fire-and-forget events. Use them when you want to signal that something happened, such as a button press or one-time action.
### Enum
Select from a fixed set of options to control states and variants. Use enums when the possible values are known ahead of time.
[Learn more](/docs/editor/data-binding/enums) about enums.
### Image

Image properties store a reference to an image, allowing you to change which image is displayed.
They are typically bound to image nodes in your design.
Use image properties when each instance needs its own image, such as user avatars, thumbnails, or dynamically loaded content.
For example, in a game or social UI, each player can have their own avatar by binding a different image to the same property.
> [!NOTE]
>
> Image properties affect a **single instance**.
>
> If you need to update an image globally across your entire file, use [asset loading instead](/docs/runtimes/loading-assets). Asset loading replaces the underlying asset, updating all instances that use it.
### Font
Font properties store a reference to a font, allowing you to change which font is displayed on a specific text style.
> [card] [Learn by remixing](https://rive.app/community/files/28431-data-binding-fonts/?utm_source=docs\&utm_medium=docs_link_card\&utm_campaign=docs_to_marketplace_links)
>
> Open this file on Marketplace, then click Remix to experiment in the Rive Editor.
> [!NOTE]
>
> Font properties affect a **single instance**.
>
> If you need to update a font globally across your entire file, use [asset loading instead](/docs/runtimes/loading-assets). Asset loading replaces the underlying asset, updating all instances that use it.
### Blob
Blob properties store a reference to a [blob asset](/docs/editor/fundamentals/assets-overview#asset-types), letting you bind arbitrary binary data, such as a custom file format, to a view model.
To bind a blob, first import a file Rive doesn't natively recognize and choose **Import as Blob**, then bind it to a Blob property.
Scripts can read and write the blob's bytes at runtime. See [Blob](/docs/scripting/api-reference/interfaces/blob) in the Scripting API reference.
### Artboard

Artboard properties let you reference an artboard and dynamically swap it at runtime.
The artboard can come from your current Rive file or be loaded from another .riv file.
To use an artboard as a property, it must first be [converted to a Component](/docs/editor/fundamentals/components#creating-a-component).
### View Model
View Model properties store a reference to a View Model instance.
They are used to create nested data structures by connecting one View Model instance to another.
For example, a `Player` View Model could contain a `Team` View Model property, allowing you to access properties such as the team's name, logo, and colors.
You can bind to and update properties on nested View Models just like top-level properties.
> [!NOTE]
>
> If you want to assign a View Model instance to a nested component, that instance must be referenced from your main View Model.
### List
List properties store collections of view model instances, which can be associated with specific artboards.
Lists are commonly used for repeating content, such as inventory items, players, messages, or generated UI elements.
For more information, see [Lists](/docs/editor/data-binding/lists).
# Stateful Components
Source: https://rive.app/docs/editor/data-binding/stateful-components
Stateful components let you expose specific view model properties directly on a nested component, so each instance can have its own values. This makes it faster to create and iterate on designs that reuse the same component with different content or styling — without wiring up a separate nested view model instance for each one.
[YouTube video player](https://www.youtube.com/embed/unMfjqrKjNc)
### Setting up a component for stateful use
Before a component can be used statefully, its artboard needs a view model with the properties you want to expose.
1. Create or open the artboard you want to use as a component.
2. Add a view model and bind the relevant properties to elements in the artboard (for example, a label string bound to a text run, or a background color bound to a fill).
3. Mark the artboard as a component using the component toggle in the inspector, or press Shift + N.
4. In the inspector, find the **Exposed Properties** section. Click + to add the view model properties you want to expose.
5. For each property, choose whether it's an Input or an Output:
* Input — the value can be set on each instance when nested as a stateful component.
* Output — the value is read-only when nested; it reports back to the parent.

### Using a stateful component
When you nest a component (press N and select it from the menu), it comes in as a stateless component by default. Switch it to a stateful component in the inspector.

Once switched to stateful, the nested view model instance selector goes away, and you'll see the exposed properties instead. Set override values directly in the inspector. Each instance of the component can have its own values for those properties.
Because the values are owned by the component instance, you don't need a separate view model instance for each one.
If the component doesn't expose any properties yet, the inspector shows a link to its source component. Click it to open the source component and add properties in its **Exposed Properties** section.
### Nesting stateful components
Stateful components can be nested inside other components. For example, a card component might contain a stateful button component.
If you want the card's parent to be able to override the button's properties, add those properties to the card's view model and data bind them to the button's stateful properties. Once added to the card's Properties panel as inputs, they'll be available to override when the card is nested.
### Output properties
Output properties report a value out of a component when it's nested. They appear with a lock icon in the inspector and are marked as read-only — you can interact with the component, but you can't set the value from outside.

To read an output value in the parent artboard, add a property to the parent's view model and data bind it (target to source) to the component's output property. The value will update in real time as the state machine runs.
### Keying input properties on Timelines
Input properties can be keyed on a timeline. Open the timeline view with a stateful component selected and you'll see a key indicator next to each exposed input property. Key the values at different points in the timeline to animate them.

[YouTube video player](https://www.youtube.com/embed/unMfjqrKjNc)
# String Template Converter
Source: https://rive.app/docs/editor/data-binding/string-template
Build text from a template and view model values.
The String Template converter fills placeholders in a template with values you bind.
The converter's input is the template, such as `You scored ${score} of ${total}`. It replaces each placeholder with the value of a matching argument. Each argument is a **Number** or a **String**, and you can bind its value to a view model property.
Store the template in a view model String property so you can change it at runtime. This helps with localization, because each language can put the values in a different order.
## Creating a string template
**1. Create the template property**
Add a String property to your view model and set its value to `You scored ${score} of ${total}`. Add Number properties for `score` and `total`.
**2. Create the converter**
In the Data panel, click the `+` button and select **Converter** > **String** > **Template**.
**3. Add arguments**
Next to **Arguments**, click the **Add Argument** (`+`) button and choose **Number** or **String**. Add one argument for each value you want to insert. For this example, add two Number arguments.
**4. Name and bind each argument**
Name the arguments `score` and `total`. Bind each argument's value to the matching view model property.
**5. Apply the converter**
Bind your text to the String property that holds the template, and set **Converter** to your string template.
**Example:**
* **Template:** `You scored ${score} of ${total}`
* **Arguments:** `score` (Number) bound to a property with the value `10`, and `total` (Number) bound to a property with the value `12`
**Result:** "You scored 10 of 12"
> [!TIP]
>
> A translated template can use the same arguments in a different order. For example, a template can place `${total}` before `${score}`.
## Placeholders
A placeholder can refer to an argument by name, by position, or by order.
| Placeholder | Uses |
| - | - |
| `${score}` | The argument named `score` |
| `${0}` | The argument at position 0 (the first argument) |
| `${}` | The next argument in order. The first `${}` uses the first argument, the second uses the second, and so on. |
The Inspector shows each argument's position next to its name. Drag an argument to change its position.
An argument name can use letters, digits, and `_`, and can't start with a digit. If two arguments have the same name, a placeholder uses the first one.
A placeholder with no matching argument adds nothing to the text.
## Formatting numbers
Add a colon and a printf-style format after the placeholder name to control how a Number argument is displayed.
| Placeholder | Value | Result |
| - | - | - |
| `${score}` | `3.14159` | `3.14159` |
| `${score:%.1f}` | `3.14159` | `3.1` |
| `${score:%,d}` | `1234567` | `1,234,567` |
| `${score:%05.2f}` | `3.14159` | `03.14` |
Without a format, numbers show up to 6 decimal places, with trailing zeros removed. The `,` flag adds thousands separators. Integer formats such as `%d` round the number. If the format is not valid, the number uses the default format.
String arguments ignore the format.
## Choosing a syntax
Use **Syntax** to choose how placeholders are written:
* `${name}` (default)
* `{name}`
* `{{name}}`
* **Custom**: set your own **Open** and **Close** delimiters. Each delimiter is 1 to 4 ASCII symbols, such as `{`, `%`, or `<`. It can't include `_`, `\`, or `:`.
If a custom delimiter is not valid, the Inspector shows a warning and the converter outputs the template as plain text.
To show the open delimiter as plain text, put a backslash before it. For example, `\${score}` displays `${score}` instead of the value. Two backslashes display one backslash.
# View Models & Instances
Source: https://rive.app/docs/editor/data-binding/view-models
A View Model defines the structure of your data. It acts as a reusable blueprint that contains a collection of properties, such as a car's color, speed, and damage.
Each property has a type, such as Number, String, Boolean, Color, Enum, or List (For more information, see [View Model Properties](/docs/editor/data-binding/view-model-properties)).
View Models do not store values themselves. Instead, values are stored in one or more View Model Instances that are created from the View Model.
For example, if you were building a racing game, you might create a Car View Model with the following [properties](/docs/editor/data-binding/view-model-properties):
```jsx theme={null}
Car (View Model)
color: Color
damage: number
make: string
speed: number
```
A single View Model can be used to create many View Model Instances. Each instance shares the same structure but stores its own values.
```jsx theme={null}
Car1 (View Model Instance)
color: 0xFFFF0000
damage: 0
make: "Subaru"
speed: 0
Car2 (View Model Instance)
color: 0xFFFF00FF
damage: .9
make: "Honda"
speed: 0
```
The properties in your instances can then be bound to elements in your designs, allowing text, images, colors, animations, state machines, and other properties to react to data changes automatically.
### Creating a View Model
A View Model defines the structure of your data. Before creating View Model Instances or setting up data bindings, you'll first need to create a View Model and add properties to it.
> [!NOTE]
>
> New Rive files come with a default view model called "ViewModel1" that is already attached to the main artboard.
**1. Add a View Model**
In the Data panel, click the `+` icon and select **View Model** or [**Global View Model**](#global-view-model-instances).
**2. Add Properties**
In the Data panel, click the **Add View Model Property** button next to the view model name and select your [property type](/docs/editor/data-binding/property-types).

## Working in the Data panel
### Templates
Templates add a View Model that's already set up for a common use. In the Data panel, click the `+` icon and select **Templates**:
* **Text Run** adds a View Model with text and text style properties, ready to bind to a text run.
### Searching
Use the search field in the Data panel to filter it by name.
### Private properties
Properties whose names start with an underscore (`_`), such as `_internalState`, are private. They're hidden from the Data panel's preview by default.
To show them, open the Data panel's header menu and check **Private properties** under **Preview**.
## Creating and editing instances
Once your View Model has been created, you can create one or more View Model Instances that store actual values for those properties.
### Creating a View Model instance
A View Model can have multiple instances. Each instance contains its own set of property values while sharing the same structure defined by the View Model.
> [!NOTE]
>
> When creating a new View Model, Rive automatically creates a View Model Instance named "Instance" so you can immediately begin testing bindings and previewing data.

**1. View existing instances**
Select a View Model in the Data panel, then click the Controls icon next to the instance name in the Inspector.
> [!TIP]
>
> To see all of your view model instances and values at once, click the Open Table Data button.
>
> 
**2. Add an instance**
Click the `+` icon to add a new instance.
**3. Name the instance**
Double click the instance's name to rename it.
**4. Update the instance data**
With the instance selected, change any of its properties.
Note that this changes **only** the values on the selected view model instance.
### Removing instances
Click the `-` icon next to the instance name to delete it.

> [!NOTE]
>
> Deleting a View Model Instance does not remove the View Model or its properties. It only removes that instance and its stored values.
To clean up a View Model, right-click it in the Data panel and select **Delete Unused Instances**. This deletes the View Model's instances that nothing in the file uses. Rive shows how many will be deleted before you confirm.
### Exporting instances
By default, exported View Model Instances are included in the .riv file. Disable Export Instance when the data is only needed during development, not in your application at runtime.

Tip
**Example - High Score**
Let's say you're building a high score screen in Rive. While designing, you'll use fake score data, but when your game is live, the high scores will be populated using real data from a database or another source.
In this case embedding the example data just increases your .riv file size.
### Using the data table
The data table shows all of a View Model's instances and their values at once. To open it, right-click a View Model in the Data panel and select **Open Data Table**, or click the **Open Table Data** button in the Inspector.
By default, each row is an instance and each column is a property. Use the table's toolbar to change the view:
* **Search** filters the table's instances by name. When the axes are flipped, it filters properties instead.
* **Flip Axes** swaps rows and columns, so instances run across the top and properties run down the side.
* **Tag Display** sets how [tags](/docs/editor/tagging) show on instances and properties: **Expanded** shows their names, **Collapsed** shows colored dots, and **Off** hides them.
Right-click an instance or property header for more options:
* **Filter Instance** or **Filter Property** shows only that instance or property.
* **Open Data Table** on a [View Model property](/docs/editor/data-binding/property-types#view-model) opens the table for the View Model it uses.
For [List](/docs/editor/data-binding/lists) properties, click the expand button in the cell to show or hide the list's items.
### Comparing a property across instances
Select one or more properties in the Data panel to see and edit their values in the Inspector. By default, the Inspector lists the values in every instance of the View Model.
Use the **Instance** menu to show **All Instances** or only one. Click the **Open Data Table** button to open the selected properties in the [data table](#using-the-data-table).
## Connecting View Model instances to Artboards
Before binding data, you'll need to decide where the data should live.
Rive supports a few common patterns:
| Pattern | |
| :- | :- |
| [Global Instances](#global-view-model-instances) | Global view models and their properties are directly accessible to all artboards |
| [Instances attached to artboards](#instances-attached-to-artboards) | The view model instance is attached to the artboard and its values can be used by that artboard and its children |
| [Instances as nested properties](#instances-as-nested-properties) | The parent view model instance stores a reference to a nested view model instance |
| [Stateful nested components](#stateful-components) | Self-contained, reusable components that store their own unique data |
### Global View Model instances
Global View Models provide data that can be accessed throughout your Rive file.
Under the hood, global view models are not connected to a specific artboard. Instead, the view model instance and its properties are directly accessible to all artboards.
[YouTube video player](https://www.youtube.com/embed/SPrxwHfPyP4)
Bindings to Global View Model properties are always **relative bindings**. This means the binding searches for a property with the same name starting from the closest View Model, rather than pointing directly to the global property.
If a closer View Model contains a property with the same name, that property will be used instead. For example, a binding to a global `scale` property will resolve to a `scale` property on a closer View Model if one exists.
Learn more about [Absolute vs Relative Binding](/docs/editor/data-binding/binding-data#absolute-vs-relative-binding).
### Instances attached to Artboards
View Model instances can be attached to a specific artboard or nested component. This is useful when only that artboard and its children need access to that data.
```
EnemyVM
├─ health
```
Tip
**Example - Game**
An Enemy view model might contain a `health` property. This property might be used by the enemy itself, but not by its parent.
### Instances as nested properties
View Models can have properties that are View Model instances.
In this pattern, the parent View Model stores references to child instances, either directly or through a [list](/docs/editor/data-binding/lists).
```
GameVM
├─ health
└─ score
└─ avatar
└─ inventory (stores an instance of InventoryVM)
InventoryVM
├─ Sword
├─ Shield
└─ Potion
```

This approach is useful when a parent artboard needs to manage a collection of items while still allowing each component to maintain its own data.
Tip
**Example - Inventory Grid**
An inventory screen might contain a list of Item View Model Instances, with each inventory slot component bound to a different item.
### Stateful components
A stateful component is an instance of a component that maintains its own data.
Unlike traditional component View Model Instances, these instances do not need to be created or referenced by the parent View Model. Instead their properties are exposed in the sidebar.

For more information, see [Stateful Components](/docs/editor/data-binding/stateful-components).
## Naming conventions
Workspace admins can set the casing that names should follow across the workspace. Open the [workspace admin](/docs/account-admin/workspaces/managing-workspaces#workspace-admin) and select the **Options** tab:
* **View model naming convention** applies to View Model and enum names. The default is `PascalCase`.
* **View model property naming convention** applies to View Model property names. The default is `camelCase`.
Choose `PascalCase`, `camelCase`, `snake_case`, `kebab-case`, or **None**. Names that don't match are listed in the [Problems](/docs/editor/interface-overview/debug-panel#problems) tab, and the AI Agent follows the convention when it creates names.
# Freehand Drawing with Pencil, Brush, Eraser, and Bucket
Source: https://rive.app/docs/editor/design/freehand-drawing
Draw, erase, and color vector artwork with the Pencil, Brush, Eraser, and Bucket tools.
Use the **Pencil**, **Brush**, and **Eraser** tools to draw with a mouse, trackpad, or stylus. These tools share many of the same drawing controls, but create or modify artwork differently. Use the **Bucket** to color in what you've drawn.
* **Brush** creates freehand paths with configurable tips and variable thickness.
* **Pencil** creates freehand paths with a consistent thickness.
* **Eraser** uses similar controls to the Brush, but removes from existing shapes rather than creating new ones.
* **Bucket** fills enclosed areas and recolors shapes with a click.
## Brush tool
Use the **Brush Tool** to draw freehand with configurable tips and
variable thickness.
Each new Brush drawing creates a Brush Shape containing a **spine**.
Unlike a standard path, a spine retains information about the brush
stroke, including its width variation and smoothing.
### Brush spines
A Brush Shape can contain one or more spines. Select the Brush Shape to view its spines in the **Brush Spines** section of the Inspector.
Each spine has its own **Width** and **Smoothing**. Changing the width preserves any width variation created while drawing.
In Design mode, select one or more spines to edit their **Position**, **Size**, and **Rotation** in the **Transform** section of the Inspector. These values can't be animated.

> [!NOTE]
>
> Use the [Shape Bend Tool](/docs/editor/design/shape-bend-tool) to adjust the width at specific points along a spine.
#### Flattening spines
Select **Flatten** to bake all spines into regular vector geometry.

### Drawing options
Use the options at the top of the panel to control how the Brush behaves while drawing.

* **Pen Pressure** varies the width of the brush based on pressure from a supported stylus.
* **Velocity** varies the width of the brush based on how quickly you draw. It applies when **Pen Pressure** is off or unavailable. Slow strokes draw at the full **Size**, and fast strokes draw thinner. With both options off, the width stays constant.
* **Hide Bounding Box** hides the selection bounding box while drawing.
### Color
Use **Color** to set the color and opacity of new brush strokes. Picking a new color starts a new Brush Shape, even when [Add to Selected](#add-to-selected) is on.
### Brush Tip
Use **Tip** to choose the shape of the Brush. Rive includes a selection of predefined brush tips.
> [!NOTE]
>
> Brush tips maintain a fixed orientation as you draw and don't rotate with the direction of the stroke.
### Size and width
Use **Size** to set the maximum width of the Brush.
**Min Width** sets the minimum width the Brush can reach when **Pen Pressure** or **Velocity** is enabled. Increase the value for more consistent strokes, or decrease it for greater variation in width.
### Smoothing
Use **Smoothing** to reduce small variations in the path as you draw, creating smoother curves.
Higher values produce smoother paths, while lower values more closely follow the movement of the pointer.
### Stabilize
Use **Stabilize** to smooth your drawing by adding distance between the pointer and the path as you draw. Higher values increase this distance, giving the path more time to smooth out changes in direction.
#### Show Leash
Enable **Show Leash** to display the distance between the pointer and the path while drawing.

### Add to Selected
Enable **Add to Selected** to add each new stroke as a spine in the selected Brush Shape instead of creating a new Brush Shape.
This lets you build up a single shape with multiple brush strokes.
## Pencil tool
Use the **Pencil Tool** to draw freehand paths with a consistent thickness. Pencil creates the same type of path and stroke as the [Pen Tool](/docs/editor/fundamentals/pen-tool-overview), but lets you create the path by drawing freehand rather than placing vertices manually.
The Pencil shares many of the same controls as the Brush, including **Smoothing**, **Stabilize**, **Show Leash**, **Hide Bounding Box**, and **Add to Selected**. It does not support brush tips, variable width, **Pen Pressure**, or **Velocity**.
Use **Color** to set the color and opacity of new pencil strokes. As with the Brush, picking a new color starts a new shape, even when **Add to Selected** is on.
### Thickness
Use **Thickness** to set the width of the stroke.
## Eraser tool
Use the **Eraser Tool** to remove portions of existing shapes by drawing over them. Like the Brush Tool, the Eraser uses a **spine**, allowing it to use configurable tips and variable width.
The Eraser shares many of the same controls as the Brush, including **Tip**, **Size**, **Min Width**, **Smoothing**, **Stabilize**, **Hide Bounding Box**, **Pen Pressure**, and **Velocity**. It does not include **Color**, **Show Leash**, or **Add to Selected**.
### Simplify
Use **Simplify** to clean up the outline left behind when erasing flattened shapes. Higher values simplify the resulting path more aggressively.
Simplify only affects flattened shapes, which are erased destructively. Brush shapes are erased non-destructively and aren't affected by this setting.
> [!TIP]
>
> Hold `⌘` (or `Ctrl` on Windows) to temporarily switch to the [Shape Bend Tool](/docs/editor/design/shape-bend-tool) and see how **Simplify** affects the number of vertices created while erasing.
## Bucket tool
Use the **Bucket Tool** to color in your artwork with a single click.
**Step 1**
Select the **Bucket Tool** or press Shift + U .
**Step 2**
Choose a color.
**Step 3**
Click the area you want to color.
What happens depends on where you click:
* **Inside an enclosed gap**, such as the inside of a closed outline: the Bucket creates a new shape that fills the gap, placed just below the artwork. The original shape isn't changed. If you've already filled that gap, the Bucket recolors the fill instead.
* **Inside an open Brush or Pencil stroke**: the stroke doesn't need to be closed. The Bucket fills the area between the stroke and a straight line joining its two ends, so an open arch fills across its open side.
* **On a Brush stroke**: the Bucket recolors the stroke.
* **On a shape or text**: the Bucket recolors its top fill. If the fill is a gradient, every stop takes the new color.
The Bucket skips hidden and locked objects. In Animate mode, recoloring a fill keys the new color.
# Rulers & Guides
Source: https://rive.app/docs/editor/design/rulers-and-guides
Use rulers, guides, grids, and snapping to align and organize content on your artboards.
Use ruler guides to place individual horizontal or vertical guides, or use guides to create structured rows, columns, and grids. Guides are specific to the artboard they're created on and are only visible in the editor—they aren't included in the exported `.riv` file.
* **Show or hide:** Click the **eye** icon next to a guide.
* **Remove:** Click the **-** icon to remove the guide.

## Toggling ruler and guide visibility
To show or hide rulers and guides, press **;** or select **View Menu > Rulers & Guides**.
## Ruler Guides
Ruler guides are horizontal or vertical guides that you can position anywhere on an artboard. Ruler guides belong to the artboard they're created on, so each artboard can have its own set of guides.
[YouTube video player](https://www.youtube.com/embed/uePyLZfrB7E)
### Creating a Ruler Guide
With rulers visible, click and drag from a ruler into the viewport to create a ruler guide.
### Managing Ruler Guides
* **Move:** Click and drag a ruler guide.
* **Duplicate:** Hold **Alt/Option** while clicking and dragging a ruler guide.
* **Delete:** Select a ruler guide and press **Delete**.
* **Lock:** Press **Option + ;** or select **View Options > Lock Guides** to prevent ruler guides from being moved.
* **Clear all:** Select **View Options > Clear Ruler Guides** to remove all ruler guides.
## Guides
Guides let you add rows, columns, or a grid to an artboard. Like ruler guides, they belong to the artboard they're created on.
### Creating a guide
With an artboard selected, go to the **Guides** panel in the Inspector and click the **+** button. Choose the type of guide you want to add:
* **Rows**
* **Columns**
* **Grid**

### Guide options
The available options depend on the guide type.
**Grid**
* **Color** - Set the color of the grid.
* **Size** - Set the size of the grid.
**Rows and Columns**
* **Color** - Set the color of the guides.
* **Count** - Set the number of rows or columns.
* **Width** - Set the width of each row or column.
* **Type** - Control how the rows or columns are distributed within the artboard: **Left**, **Right**, **Center**, or **Stretch**.
### Managing guides
You can add multiple guides to the same artboard, allowing you to combine grids, rows, and columns.

* **Show or hide:** Click the **eye** icon next to a guide.
* **Remove:** Click the **-** icon to remove the guide.
### Guide Components
You can convert the guides on an artboard to a component, allowing you to reuse the same guide configuration across multiple artboards.
In the **Guides** panel of the Inspector, click the **Component** icon. The guides on the artboard are converted to a component and added to the Assets panel.
To edit the guide component, select it in the **Assets** panel. Changes to the component are reflected on every artboard where it's used.
#### Applying a Guide Component
To apply a guide component to an artboard, drag it from the **Assets** panel onto the artboard.
To apply it to every artboard in the file, right-click the component in the **Assets** panel and select **Apply to All Artboards**.
#### Managing a Guide Component
When an artboard uses a guide component, you can manage it from the **Guides** panel in the Inspector.
* **Show or hide:** Click the **eye** icon to toggle the component's visibility.
* **Remove:** Click the **-** icon to remove the component from the current artboard.
* **Detach:** Detach the guides from the component to edit them independently on the current artboard.
## Snapping
Enable snapping to make objects snap to guides and ruler guides as you position them.
Press **Option + ;** or open **View Options** and enable **Snapping**.
# Shape Bend Tool
Source: https://rive.app/docs/editor/design/shape-bend-tool
Bend and reshape paths by dragging their edges.
Use the **Shape Bend Tool** to reshape paths and Brush strokes by dragging directly on their geometry. Drag a shape’s edge to bend it, or on a Brush Shape, drag the center line to reshape the stroke and its edges to adjust its width. Corner points act as anchors while the geometry between them bends.
## Bending shapes
Select the **Shape Bend Tool**, then drag an edge to bend the path.
As you drag, nearby corner points anchor the bend while the path between them reshapes. Use **Corner Threshold** and **Falloff** to control which points act as corners and how far the bend extends.
### Brush shapes
The Shape Bend Tool can also edit the spine and width of Brush Shapes.
* Drag the center line to reshape the stroke.
* Drag either edge to change the width of the stroke.
> [!TIP]
>
> While using the **Brush Tool**, hold ⌘ (or Ctrl on Windows) to temporarily switch to the **Shape Bend Tool**.
## Bend Options
### Corner Threshold
**Corner Threshold** controls how sharp a point must be to act as a corner while bending. Corners remain fixed while the path between them bends.
Lower values identify more points as corners.
### Falloff
**Falloff** controls how far a bend spreads along the path, as a percentage of the outline.
Higher values allow the bend to affect more of the path. Corners can stop the bend before it reaches the full falloff distance.
### Smooth Joins
Enable **Smooth Joins** to keep the path smooth where the bent section meets the rest of the path.
Disable it to allow the bend to create a sharp point at the join.
## View options
Use the view options to inspect the geometry and curvature of the path while working with the Shape Bend Tool.
### Show Points
Enable **Show Points** to display the points along the path.
### Show Curvature
Enable **Show Curvature** to display a comb along the path that visualizes its curvature. Longer lines indicate tighter curves, while sudden changes in the comb indicate abrupt changes in curvature.
Use **Comb Scale** to adjust the size of the curvature visualization.
Enable **Comb Outline** to connect the ends of the comb lines, making changes in curvature easier to see.
### Show Selection
Enable **Show Selection** to display the selection outline and bounding box while bending.
# Shape Builder
Source: https://rive.app/docs/editor/design/shape-builder
Merge and subtract vector shapes.
The Shape Builder tool lets you create new shapes by combining or subtracting vector shapes. Instead of editing paths manually, you can drag across regions to merge them or remove unwanted sections.
[YouTube video player](https://www.youtube.com/embed/dhT1ZiubXxU)
> [card] [Learn by remixing](https://rive.app/community/files/28403-shape-builder/?utm_source=docs\&utm_medium=docs_link_card\&utm_campaign=docs_to_marketplace_links)
>
> Open this file on Marketplace, then click Remix to experiment in the Rive Editor.
**1. Select your shapes**
Select two or more vector shapes.
**2. Activate the Shape Builder tool**
Click the **Shape Builder** tool from the **Create Tools** menu in the Toolbar or press **Shift** + **M**.
**3. Merge regions**
Drag across adjacent regions to merge them into a single shape.
**4. Subtract regions**
Hold Alt (Windows) or Option (macOS) while dragging or clicking to remove regions from the shape.
# Sharing & Embedding
Source: https://rive.app/docs/editor/embed-urls/overview
Share your Rive files with a hosted link or embed them in websites and other platforms.
> [!NOTE]
>
> Generating embed URLs is available on Voyager and Enterprise plans. [Learn more about our plans and pricing](https://rive.app/pricing?utm_source=docs\&utm_medium=content).
Embed URLs let you quickly generate a shareable version of your file for embedding or sharing.
An embed URL is a **snapshot** of your file at the moment it’s generated. If you make changes later, you’ll need to generate a new link to reflect those updates.
> [!NOTE]
>
> Embeds use iframes and don't provide access to Rive's runtime APIs. If you need to control or interact with your Rive programmatically, use a [Rive runtime](/docs/runtimes/getting-started) instead.
## Creating an embed URL
**1. Open the Embed URL dialog**
In the Rive editor, click the **main menu** in the top-left corner and select **Generate Embed URL**.

**2. Generate your link**
In the dialog that appears, choose the artboard and state machine or timeline animation to display, and click **Generate Link**.

**3. Set your options**
* **Enable** — Turn the link on or off to control access.
* **Rive Renderer** — Use the Rive Renderer (recommended) or Canvas renderer.
* **Multi-touch** — Enable support for multi-touch interactions.
> [!NOTE]
>
> Certain features, such as [Vector Feathering](/docs/editor/fundamentals/vector-feathering), are only available using the Rive Renderer. See our [Feature Support](/docs/feature-support) page for more information.

**4. Choose a link type**
Select the option that best fits how you plan to use your file.
> [!NOTE]
>
> For more information on using embed URLs with tools like Framer, Webflow, and Notion, see [Integrations](/docs/integrations/overview).
* **Hosted link** — Opens your file on a dedicated Rive page with a framed viewer. Ideal for sharing with clients or stakeholders.
* **Embed link** — Displays your file without the surrounding Rive UI. Useful for platforms that automatically preview links, such as Notion and Telegram.
* **Embed code** — An iframe snippet for embedding your file into sites where you can edit HTML, such as WordPress.
* **Framer code (Deprecated)** — See the new official [Rive Framer Plugin](https://www.framer.com/marketplace/plugins/rive/).
## Sharing on social media
Copy the **Hosted Link** and paste it into a supported social platform. The link includes metadata that allows supported platforms to display a preview of your Rive file.
## Managing embed URLs
Visit the [Embed URLs](https://rive.app/account/links?utm_source=docs\&utm_medium=content) section of your settings to manage the links you've generated. You can disable an embed URL by turning off **Active**.
# Audio Events
Source: https://rive.app/docs/editor/events/audio-events
Play short sound effects from timelines, transitions, and listeners.
An Audio Event plays a sound when it fires. Use it for short sound effects, such as button clicks, pops, and footsteps, that start in sync with an animation or a user interaction. Sounds from several Audio Events can play over each other.
> [!NOTE]
>
> Audio Events are built for quick sounds. There are no runtime controls for the sound: you can't pause it or change its volume or panning while it plays. For background music, voice-overs, and other long or controlled audio, use [Scripting](/docs/scripting/getting-started) with [AudioSound](/docs/scripting/api-reference/interfaces/audio-sound) and [AudioSource](/docs/scripting/api-reference/interfaces/audio-source).
[YouTube video player](https://www.youtube.com/embed/62j3fbNgxFY)
## Creating an Audio Event
Drag an audio asset or clip from the [Assets panel](/docs/editor/assets/audio) onto the stage. Rive creates an Audio Event that plays that sound.
To turn an existing event into an Audio Event, select it, set **Type** to **Audio** in the Inspector, and choose a sound in the **Asset** field under **Audio Properties**. You can create a new event with the Event tool (Shift + E ).
To import sounds, browse the Soundly library, make clips, or adjust a sound's volume, see [Audio Assets](/docs/editor/assets/audio).
## Playing an Audio Event
An Audio Event plays its sound whenever it's reported. Like any [event](/docs/editor/events/overview#signaling-an-event), you can report it from:
* **A timeline**, to play the sound at an exact frame.
* **A state or transition**, to play the sound when the State Machine enters a state or makes a transition.
* **A listener**, to play the sound in response to the user, such as a click on a shape.
## Monitoring levels
The VU meter at the bottom of the Inspector shows the audio output level. If the peaks turn red, the output is clipping, often because several sounds are playing at once. Lower the volume of your audio assets to give them more headroom.
# Events Overview
Source: https://rive.app/docs/editor/events/overview
Creating and signaling Rive Events
Events live within an artboard and are used to signal that something has happened. They can be fired from timelines, states, transitions, or listeners, and a [listener](#listening-for-an-event) can respond when an event fires.
Rive supports three types of Events:
* [Open URL Event](/docs/editor/events/open-url-events) — Opens a URL at runtime
* [Audio Event](/docs/editor/events/audio-events) — Plays a sound
* General Event — Signals that something happened, with no built-in behavior. Use it to trigger a listener.
> [!NOTE]
>
> Using events to send information to runtime code is deprecated. Use [Data Binding](/docs/editor/data-binding/overview) instead. See [Events at Runtime](/docs/editor/events/general-events) for legacy projects.
## Creating an event
**1. Create an Event**
Use the Events tool located in the Toolbar and click anywhere on the artboard.

You'll notice that the Event is displayed on the artboard and in the Hierarchy.
**2. Name your Event**
Give your event a name so it’s easy to identify and reference.
You can rename it using the **Name** field, or by double-clicking the name directly on the artboard.

**3. Select an Event type**
The Type dropdown allows you to change the Event type between Audio, URL, and General.

**4. Set your Event Properties**
Each Event type has its own set of properties.
For more information on the specific event types, see [Open URL Events](/docs/editor/events/open-url-events) and [Audio Events](/docs/editor/events/audio-events). Custom properties on General Events are only used by runtime code, which is deprecated. See [Events at Runtime](/docs/editor/events/general-events).
> [!TIP]
>
> If events aren't visible on the stage, open the **View Options** menu and make sure **Events** is enabled.
## Signaling an event
We can signal an Event in four ways: from a timeline, a listener, a state, or a transition.
### Timeline
Signaling an Event from the timeline lets you control the exact moment in an animation when the Event fires.
First, select the timeline you want to add the Event to. Then use the **Report Event** button in the Inspector.

### Transition & state
You can report an event on a Transition or a State. To report an event, select the desired State or Transition and use the `+` button next to the Events section in the Inspector.

Now that we've selected the Event, we can decide whether it is signaled at the start or end of the Transition or State.
The **Fire** dropdown lists both Rive events and view model triggers, so you can use it to fire a view model trigger instead of reporting an event.
### Listeners
With your [Listener](/docs/editor/state-machine/listeners) selected, click the `+` below the State Machine Graph, and select **Report Event**.

## Listening for an event
A [listener](/docs/editor/state-machine/listeners) can respond when an event fires, then run actions such as changing a value or reporting another event.
**Step 1**
Create a listener in the State Machine and set its target to the artboard or nested component that contains the event.
**Step 2**
Set **Listen to** to **Rive Event**, then select the event.
**Step 3**
Add the actions you want to run when the event fires.
The listener target must be an artboard or nested component, not an element. See [Rive Event listeners](/docs/editor/state-machine/listeners#rive-event) for details.
> [!TIP]
>
> To communicate between artboards, such as between a parent artboard and a nested component, we recommend [Data Binding](/docs/editor/data-binding/overview) instead of events.
# Exporting for Backup
Source: https://rive.app/docs/editor/exporting/exporting-for-backup
Download a .rev backup of a file to keep a local copy or send it to Rive support.
> [!NOTE]
>
> A backup is a snapshot, so it doesn't stay in sync with the original file. Depending on what you need, another option may suit you better:
>
> * **To share a file with someone,** [invite them](/docs/editor/interface-overview/toolbar#invite) to the file, or add them to the project that contains it. They'll always see the latest version.
> * **To keep a file in source control,** use the [Rive CLI](/docs/cli/overview) to convert it to [Rive Markup Language (RML)](/docs/runtimes/advanced-topic/rml), a text format that diffs and merges like code and stays linked to the original file.
> * **To go back to an earlier version of a file,** use [Revision History](/docs/editor/fundamentals/revision-history).
A backup is a `.rev` file: a complete copy of a Rive file that you can import back into the Editor and keep editing. Unlike a [runtime export](/docs/editor/exporting/exporting-for-runtime) (`.riv`), which strips out everything your app doesn't need, a backup keeps all of the Editor data.
Export a backup when you want to:
* Keep a local copy of a file on your computer.
* Send a file to Rive support with a support ticket.
Exporting and importing backups are available on paid plans. [Learn more about our plans and pricing](https://rive.app/pricing?utm_source=docs\&utm_medium=content).
## Exporting from the File Browser
**Step 1**
In the [File Browser](/docs/editor/interface-overview/file-browser), find the file you want to back up.
**Step 2**
Right-click the file and select **Download Backup** to download the current version.
To download an earlier version instead, open **Download Revision** and select a revision.

## Exporting from an open file
**Step 1**
Open the Editor Menu.
**Step 2**
Select **Export** > **For Backup**.

## Importing a backup
**Step 1**
Open the File Browser and go to the project or folder where you want the file.
**Step 2**
Drag the `.rev` file from your computer into the File Browser.
The backup is imported as a new file. It doesn't replace or update the original.
# Exporting for Runtime
Source: https://rive.app/docs/editor/exporting/exporting-for-runtime
Export a production-ready .riv file to ship in apps, games, websites, and other supported runtimes.
> [!NOTE]
>
> Every plan can export for runtime. On the Free plan, exported files play a Rive splash screen; paid plans export without it. [Learn more about our plans and pricing](https://rive.app/pricing?utm_source=docs\&utm_medium=content).
A `.riv` file is the production-ready version of your Rive file. It isn't a design file, a mockup, or a prototype to hand off and rebuild. It's the final asset that ships in your product. Your artboards, animations, state machines, data binding, and scripts all run at runtime exactly as you built them.
The same `.riv` file works across every supported runtime, including web, mobile, and game engines. Load it with any of Rive's [open source runtimes](/docs/runtimes/).
## Exporting a .riv file
[YouTube video player](https://www.youtube.com/embed/H_px35jTqhg)
**Step 1**
Click **Publish** on the right side of the toolbar and choose **To .riv**.
You can also open the main menu in the left of the toolbar and choose **Export** > **For Runtime**.
**Step 2**
In the dialog that opens, click **Export your Rive file**.
On a paid plan, turn on **Skip this modal next time** to export directly in the future.
**Step 3**
Add the downloaded `.riv` file to your app, game, or website, and load it with a [runtime](/docs/runtimes/).
> [!TIP]
>
> To save an editable copy of your file, export it **For Backup** as a `.rev` file instead.
## Using newer files with older runtimes
Rive files are built for backwards compatibility. A file exported from the latest version of the editor can still load in older runtimes.
If a file uses a feature that was added after your runtime version was released, that specific feature may be skipped, while the rest of the file continues to run.
For full [feature support](/docs/feature-support), fixes, and performance improvements, keep your runtime up to date.
# Exporting Videos & Images
Source: https://rive.app/docs/editor/exporting/exporting-for-video-and-static-design
Render artboards, timelines, and State Machines to video, GIF, and image formats with the Cloud Renderer.
> [!NOTE]
>
> Exporting video and images is available on paid plans. [Learn more about our plans and pricing](https://rive.app/pricing?utm_source=docs\&utm_medium=content).
Rive is built for interactive animation, but sometimes you need a traditional format such as an MP4, a GIF, or a PNG. The Cloud Renderer creates these files on Rive's servers, so you can keep working while your render runs.
Rendering has two parts:
* **Render presets** are saved settings for a render, such as what to render, the format, and the size. They belong to an artboard.
* The **Render Queue** is where you start renders and download the finished files.
## Supported formats
The available formats depend on the preset's mode.
| Mode | Formats |
| - | - |
| **Design** (a still image) | PNG, SVG |
| **Animation** or **State Machine** (over time) | H.264 (`.mp4`), WebM, GIF, PNG sequence, SVG sequence |
PNG and SVG sequences download as a `.zip` file with one image per frame.
## Creating a render preset
**Step 1**
Select the artboard you want to render.
**Step 2**
In the **Render Presets** section of the Inspector, click **+**.

**Step 3**
Click the options icon to the left of the preset name, then set the preset's options.

You can change a preset's format at any time from the dropdown next to its name.

### Preset options
* **Name**: The name of the preset.
* **Mode**: What to render.
* **Design** renders a still image of the artboard.
* **Animation** renders a single timeline. Choose it under **Timeline**.
* **State Machine** renders a State Machine as it plays over time. Choose it under **State Machine**.
* **Format**: The file format. For Animation and State Machine presets, also set the frame rate.
* **Duration**: How long to render, plus a multiplier (**1x**, **2x**, **3x**, or a custom value). Available for Animation and State Machine presets.
* **Bit rate**: The video quality for H.264 and WebM. Leave it on **Auto**, or enter a custom value in kbps.
* **Size**: Use **Auto** to render at the artboard's size, or choose a custom width and height.
## Rendering
**Step 1**
Add presets to the Render Queue in any of these ways:
* Click **Queue All** below the presets to add every preset on the artboard.
* In a preset's options, click **Add to Render Queue**.
* To add a preset and start rendering right away, click **Queue and Start Render** in the preset's options, or click the play button next to the preset's name.
The Render Queue opens when you add a preset.

**Step 2**
On the **Queued** tab, check each render's settings. Expand a render to change its options for that render only, such as **Matte**, the background color, or the **View Model** instance to render with.
**Step 3**
Click the play button next to a render to start it, or click the double play button at the top of the Render Queue to start every queued render.

**Step 4**
When a render finishes, open the **Completed** tab and click the download button next to it.

To reopen the Render Queue later, open the Editor Menu and select **Open Render Queue**.
> [!TIP]
>
> You can also add a timeline straight to the Render Queue: right-click it in the Animations list and select **Add to Render Queue**.
# Align and Distribute
Source: https://rive.app/docs/editor/fundamentals/align-and-distribute
Align objects to the artboard or to each other.
[YouTube video player](https://www.youtube.com/embed/LBB3BDo5pR4)
Use align and distribute tools to quickly position objects on the artboard or space multiple objects evenly.
When you select one or more objects, the align and distribute tools appear in the Inspector.
## Align
Align tools let you align objects to the left, right, top, bottom, or center.
When a single object is selected, the object aligns to the artboard. When multiple objects are selected, the selected objects align to each other.
### Align to a key object
With two or more objects selected, click one of them again to make it the Key Object, shown with a heavier outline. Aligning then moves the other selected objects to it, while the Key Object stays in place. Click it again to clear it.
## Distribute
Distribution tools appear when multiple objects are selected.
Use distribution to space selected objects evenly, either horizontally or vertically. This is useful when creating repeated elements, button groups, icon rows, or other layouts where objects should have consistent spacing.
# Artboards
Source: https://rive.app/docs/editor/fundamentals/artboards
Learn how to create, manage, and configure artboards in Rive.
[YouTube video player](https://www.youtube.com/embed/xdqqPAlB4n8)
Artboards are the foundation of your composition across both [Design and Animate mode](/docs/editor/fundamentals/design-vs-animate-mode). Each artboard defines a scene with its own dimensions, background, hierarchy, animations, and state machines.
Every Rive file contains at least one artboard, but you can create any number of artboards on the [Stage](/docs/editor/interface-overview/stage).
Artboards can also be converted to [components](/docs/editor/fundamentals/components), allowing you to create and control multiple instances of an artboard within your composition.
## Creating Artboards
### From a new Rive file
When you create a new Rive file, you'll be prompted to create an artboard. Choose a size from one of the presets, or enter a custom width and height. You can resize the artboard at any time.

The width and height define the artboard's dimensions in the editor. At runtime, the artboard is drawn at whatever size its container is, so its displayed size and aspect ratio can differ. See [Artboard size at runtime](#artboard-size-at-runtime).
### Creating additional Artboards
A Rive file can contain multiple artboards.
**Step 1**
Select the **Artboard Tool** or press **A**.
**Step 2**
Click and drag anywhere on the stage to create an artboard.
Artboards can't be nested directly inside other artboards. To nest an artboard, first convert it to a [component](/docs/editor/fundamentals/components).
### Copying Artboards
Select an artboard and press **Cmd/Ctrl + D** to duplicate the artboard and all of its contents.

## Artboard size at runtime
The artboard's width and height don't set its size in your app or game. At runtime, Rive draws the artboard into a container, such as a canvas or a view, and the container's size comes from your app. The **fit** mode, which you set in the runtime, decides how the artboard fills that container.
Artboard dimensions are measured in units rather than pixels. If a 500-unit-wide artboard is displayed 1000 pixels wide, each unit covers 2 pixels. While you work in the editor, you can usually treat units like pixels.
### Responsive graphics: use Layout
If your graphic should adapt to different screen sizes, orientations, or container sizes, build it with [Layouts](/docs/editor/layouts/layouts-overview) and set the fit mode to **Layout** at runtime.
With **Layout**, the runtime doesn't scale the artboard. It resizes the artboard to match the container, and the artboard's Layouts decide how the content moves and resizes, the same way they do when you resize the artboard in the editor. To make the content larger or smaller within the container, set a layout scale factor at runtime.
> [!NOTE]
>
> The **Layout** fit mode only works well if the artboard is built with Layouts. Content that isn't inside a Layout won't respond to the new size.
### Fixed-size graphics: scaling fit modes
The other fit modes scale the whole artboard as a single image. Use them for graphics that should keep the same composition at any size, such as an illustration or a logo animation:
* **Contain** (the default) scales the artboard until it fits inside the container while keeping its aspect ratio. If the aspect ratios don't match, empty space is left on one axis.
* **Cover** scales the artboard until it fills the container while keeping its aspect ratio. If the aspect ratios don't match, content is cropped on one axis.
* **Fill** stretches the artboard to the container's width and height, distorting it if the aspect ratios don't match.
* **None** draws the artboard at its original size without scaling.
Because **Contain** is the default, a responsive artboard won't respond to the container until you change the fit mode to **Layout**.
Tip
**Example - A 500 × 500 artboard in a 1000 × 500 container**
* **Layout:** The artboard becomes 1000 × 500 units, and its Layouts reposition and resize the content to fit the wider space.
* **Contain:** The artboard is drawn at 500 × 500 pixels, with 250 pixels of empty space on the left and right.
* **Cover:** The artboard is scaled to 1000 × 1000 pixels, and 250 pixels are cropped from the top and bottom.
* **Fill:** The artboard is stretched to 1000 × 500 pixels, so everything looks twice as wide.
When a scaling fit mode leaves empty space, the runtime's **alignment** setting decides where the artboard sits in the container, such as centered or top-left.
For every fit mode and how to set it on each platform, see [Runtime layout](/docs/runtimes/layout).
## Managing Artboards
Each artboard has its own hierarchy, animations, state machines, and properties.
### Selecting and renaming artboards
Each artboard's name appears above it on the stage. Click the name to select the artboard. Double-click it to rename the artboard.
### Hierarchy
Each artboard has its own hierarchy containing the objects that belong to that artboard. Select an artboard to view its hierarchy in the Hierarchy panel.
See [Hierarchy](/docs/editor/interface-overview/hierarchy) for more information about organizing and navigating objects.
### Animations & State Machines
Animations and state machines belong to individual artboards. Select an artboard to view and edit its animations and state machines.
See [Animations](/docs/editor/animate-mode/animate-mode-overview) and [State Machines](/docs/editor/state-machine/state-machine) to learn more.
### Spaces
Spaces group artboards so you can organize large files. Each space has its own stage view, so you only see the artboards in the space you're working in. Spaces only organize your work in the editor. They aren't exported.
See [Spaces](/docs/editor/interface-overview/hierarchy#spaces) to learn how to create spaces and move artboards between them.
## Artboard properties
Select an artboard to view and edit its properties in the Inspector.

* **Transform** - Set the artboard's position, size, scale, rotation, and origin.
* **Layout** - Control how the artboard responds when its size changes. See [Layout](/docs/editor/layouts/layouts-overview).
* **Fill** - Set the artboard's background color.
* **Model** - Choose the [view model](/docs/editor/data-binding/binding-data) associated with the artboard.
* [Clip](#clip) - Control whether content outside the artboard's bounds is visible.
### Clip
Enabling the **Clip** toggle hides content that extends beyond the bounds of the artboard.
> [!WARNING]
>
> Clipping can be expensive to render, so only enable it when needed.
In most cases, you don't need to enable **Clip** on a top-level artboard because content outside its bounds isn't rendered at runtime.

## Default Artboard & State Machine
The default artboard and state machine are used at runtime when an artboard or state machine isn't explicitly specified.
To change the default, use the dropdown to select the artboard and state machine you want to use.

You can also set the default from the toolbar. Click the arrow next to the play button, then choose an artboard and one of its state machines. The default is also what plays when you preview in the editor. Click the play button, or press Shift + Space , to play the default state machine.
# Assets
Source: https://rive.app/docs/editor/fundamentals/assets-overview
Assets are reusable resources in a Rive file. Some assets are imported from external files, such as images, fonts, audio, and custom blobs. Others are created in Rive, such as scripts and components.
This page focuses on imported file assets. For these assets, you can control whether the asset is included in the exported .riv file, loaded separately at runtime, or excluded from the export.
For other asset types, see [Scripts](/docs/scripting/getting-started) and [Components](/docs/editor/fundamentals/components).
## Assets Panel
Use the Assets panel to find, manage, and create assets in your file. The panel includes imported file assets, such as images, fonts, audio, and blobs, along with assets created in Rive, such as scripts and components.
Use the panel to import new assets, create Rive assets, sort and filter by type, and select an asset to view its settings in the Inspector.
[YouTube video player](https://www.youtube.com/embed/B9uD-Gh8zjg)
* **Search:** Click the search button in the panel header to filter the Assets panel by name.
* **Generate Artboard:** Right-click an image or other visual asset and select **Generate Artboard** to create a new artboard sized to fit it.
### Asset status
The Assets panel marks assets that aren't ready to use. An asset can be:
* **Processing:** The asset is still uploading or being processed. It's ready to use once its status clears.
* **Not Downloaded:** The asset hasn't been downloaded yet. Click the download icon to load it.
* **Asset Not Found:** The asset's file couldn't be loaded. [Replace](#information) it, or upload the file again.
## Asset types
Imported file assets include:
* **Raster images:** JPEG, PNG, WebP
* [Photoshop files](/docs/editor/assets/psd): PSD
* [SVG files](/docs/editor/assets/svg): Vector artwork imported as editable Rive content
* [Fonts](/docs/editor/text/fonts): TTF, OTF
* [Audio](/docs/editor/assets/audio): MP3, WAV, FLAC
* [Lottie](/docs/editor/assets/lottie): `.lottie` files, available on Enterprise plans
* **Blob assets:** Advanced custom assets
> [!NOTE]
>
> Blob assets are useful for advanced workflows where a script needs access to a custom file type, such as a 3D model.
## Importing assets
### Drag and drop
You can import assets by dragging files into Rive or by using the Assets panel.
If the file type is not directly supported, Rive asks if you want to import it as a custom blob asset.
### Browse files
To import from the Assets panel, click **+**, then choose the asset you want to import.

### Asset-specific workflows
* [SVG Files](/docs/editor/assets/svg) for importing SVGs from Figma, Illustrator, and other vector tools.
* [Photoshop Files](/docs/editor/assets/psd) for importing layered PSD files.
* [Flash and Animate Files](/docs/editor/assets/flash) for converting `.fla` and XFL files into Rive files.
* [Font Files](/docs/editor/text/fonts) for adding custom and Google Fonts.
* [Audio Assets](/docs/editor/assets/audio) for browsing sounds, importing audio, and creating clips.
## Asset settings
Select an asset in the Assets panel to view its settings in the Inspector. The available settings depend on the asset type.
Asset settings panels can include:
* [Information](#information): Details about the selected asset.
* [Compression](#compression): Image compression settings for raster images and PSD files.
* [Export Options](#export-options): Settings that control how the asset is handled when exporting a `.riv` file.

### Information
The **Information** panel shows details about the selected asset, such as file size, dimensions, usage count, and creation date. Edit **File Name** to rename the asset in the Assets panel.
Use **Replace** to swap the source asset without changing how the asset is used in the Rive file. For example, replacing an image updates the asset everywhere it is used.
The information shown depends on the asset type:
* **Fonts** can show family, style, supported scripts, publisher/designer information, license details, and glyphs.
* **Audio** can show volume, format, channels, sample rate, duration, and an audio preview.
### Image sampling and wrapping
Raster images have **Filter**, **Wrap X**, and **Wrap Y** settings in the **Information** panel. They set how the image is sampled, and act as the default for every image object that uses the asset.
**Filter** controls how the image is sampled when it's scaled:
* **Bilinear** (default): smooth.
* **Nearest**: hard pixels, good for pixel art.
**Wrap X** and **Wrap Y** control how the image is sampled past its horizontal and vertical edges:
* **Clamp** (default): stretch the edge pixels.
* **Repeat**: tile the image.
* **Mirror**: tile the image, flipping every other copy.
Image objects on the stage have the same settings in the Inspector, plus **Inherit**. **Inherit** (default) uses the asset's setting. Choose another option to override it for that image.
### Compression
Raster images and PSD files include a **Compression** panel. Use compression settings to control how the asset is encoded in the exported `.riv` file.
Choose a compression format, then adjust the **Quality** value to balance image quality and file size. WebP is recommended for most raster images because it usually provides smaller file sizes while preserving good visual quality.
### Export options
Export options control how an imported asset is handled when you export a .riv file for runtime. Use these settings to decide whether an asset is included in the .riv file, loaded separately at runtime, or excluded from the export.
The available export options depend on the asset type.
#### Behavior
**Behavior** controls whether the asset is exported.
* **Automatic**: Export the asset if it is used in the file.
* **Force Export**: Export the asset even if it is not currently used in the file.
* **Prevent Export**: Do not export the asset, even if it is used in the file.
SVG assets only use Automatic because SVGs are converted to Rive vector objects rather than exported as separate file assets.
> [!TIP]
>
> Use **Prevent Export** when the asset is only a placeholder in the Rive file and will be replaced at runtime. For example, a profile card might use a placeholder avatar in the editor, while your app loads the real user's avatar at runtime.
>
> Use **Force Export** when an asset may not be visible or directly used in the editor, but still needs to be available at runtime. For example, a file might show one image in the editor, while your app randomly selects from a set of images at runtime.
#### Type
Type controls how the asset is included or referenced by the exported .riv file. This option is available for all imported asset types except SVGs.
* **Embedded**: Include the asset data directly in the .riv file.
* **Referenced**: Store a reference to the asset so it can be loaded separately at runtime.
* **Hosted**: Load the asset from Rive’s servers instead of embedding it in the `.riv` file. Hosted assets are available on paid Voyager plans.
#### Source
See [Audio Assets](/docs/editor/assets/audio#export-settings) for audio-specific export settings, including Source.
#### Include
See [Font Assets](/docs/editor/text/fonts#export-settings) for font-specific export settings, like Include.
# Bitmap Cache
Source: https://rive.app/docs/editor/fundamentals/bitmap-cache
Draw a component's instances from a cached image instead of redrawing their vectors every frame.
A Bitmap Cache turns a [component](/docs/editor/fundamentals/components) into an image at runtime. Each instance of the component draws its vector content once into an image, then shows that image on every frame instead of redrawing the vectors.
Use it for components with complex vector artwork that rarely changes, such as a detailed background, an illustration, or an icon repeated across a list. Drawing one image is faster than drawing many paths, so a cache can save rendering time when the same complex artwork stays on screen.
## How the cache updates
The cached image is redrawn only when it's out of date:
* **The component's content changes.** Any change inside the component, such as an animation playing, a data-bound value updating, or a property changing, redraws the image.
* **The instance's size on screen changes.** Scaling the instance or zooming the view redraws the image at the new size.
Moving or rotating an instance doesn't redraw the image.
> [!WARNING]
>
> A cache helps most with static content. A component whose content changes on every frame redraws its image on every frame, which costs more than drawing its vectors directly. Scaling an instance continuously also redraws its image often. Turn the cache off while the component animates, or don't add one.
Each instance keeps its own image, so memory use grows with the number of cached instances and their size on screen.
## Adding a Bitmap Cache
The Bitmap Cache is set on the component, and applies to every instance of it.
**Step 1**
Select the component's artboard.
**Step 2**
Click **+** next to **Bitmap Cache** in the **Inspector**.
To remove the cache, click the delete button next to **Bitmap Cache**.
Only components can add a Bitmap Cache. If the artboard isn't a component yet, [convert it to a component](/docs/editor/fundamentals/components#converting-artboards-to-components) first. Selecting several components lets you add, remove, or edit the cache on all of them at once.
> [!NOTE]
>
> The cache is meant for component instances. Don't rely on it for an artboard shown directly as the main artboard: most runtimes draw that artboard as vectors.
## Bitmap Cache properties
### Resolution
**Resolution** sets how sharp the cached image is, as a multiple of the pixels the instance covers on screen.
* `1x` is the default. The image has one pixel for every screen pixel the instance covers, so it matches the vectors at their current size.
* Values above `1x` draw a larger image that's scaled down on screen. `2x` uses four times the memory of `1x`.
* Values below `1x` draw a smaller image that's scaled up on screen. It uses less memory but looks softer.
Resolution can be set from `0.01x` to `8x`. The image is capped at 2048 pixels per side, so a large instance on a high-density screen can look softer than the value you set.
### On/Off
The toggle next to **Resolution** turns the cache on or off without removing it. When the cache is off, the component draws its vectors as if it had no cache, and its image is released from memory. Instances with a Mesh or N-Slice still draw from an image, at `1x`. See [Meshes and N-Slices on components](#meshes-and-n-slices-on-components).
You can key the toggle (it appears as **Enabled** on the timeline) or data bind it. For example, turn the cache on while a component is at rest and off while it animates. **Resolution** can also be keyed and data bound.
## Meshes and N-Slices on components
A component instance with a [Mesh](/docs/editor/manipulating-shapes/meshes) or [N-Slice](/docs/editor/layouts/n-slicing) is always drawn as an image, because the mesh deforms that image. If the component has a Bitmap Cache that's on, its **Resolution** sets the sharpness of that image. Without a cache, or with the cache off, the image uses `1x`.
For these instances, the image size follows the component's artboard size and **Resolution**, not the instance's size on screen, so scaling the instance doesn't redraw the image. If a meshed instance looks soft on a high-density screen or when it's scaled up, raise **Resolution**.
## Things to know
* The image covers the component's artboard area. Artwork that extends past the artboard's edges is cut off in cached instances, even when the artboard doesn't clip its content.
* The Bitmap Cache needs a GPU renderer: the Rive Renderer on Flutter, WebGL2 on Web and React, and GPU Canvas on Apple, Android, React Native, and C++. Without one, such as with the Web Canvas packages, the component draws its vectors normally, without caching. See [Feature Support](/docs/feature-support#runtime-support-by-feature) for supported runtimes and versions.
# Color and Gradients
Source: https://rive.app/docs/editor/fundamentals/color-and-gradients
Choose solid colors, gradients, images, and artboards for fills and strokes with the color picker.
Every [fill and stroke](/docs/editor/fundamentals/fill-and-stroke) has a paint, which can be a solid color, a gradient, an image, or an artboard. Click a fill or stroke's swatch in the Inspector to open the color picker.
## Choosing a paint type
The dropdown at the top of the color picker sets the paint type:
* **Solid**: A single color.
* **Linear**: A gradient that blends colors along a straight line.
* **Radial**: A gradient that blends colors outward from a center point.
* **Angular**: A gradient that sweeps colors around a center point. See [Angular gradients](#angular-gradients).
* **Image**: Paints with an image asset. See [Image and artboard paints](#image-and-artboard-paints).
* **Artboard**: Paints with a component artboard. See [Image and artboard paints](#image-and-artboard-paints).

## Choosing a color

* Drag in the large square to set saturation and brightness, and use the sliders to set the hue and opacity.
* Type a hex value, or set the **R**, **G**, and **B** channels separately.
* Click **Pick Color from Stage** and click anywhere on the stage to use that color.
Colors can be keyed on a timeline and [bound to data](/docs/editor/data-binding/overview). The **R**, **G**, **B**, and alpha channels can also be keyed and bound one at a time, for example to animate only a color's red channel.
## Editing gradients
When the paint type is **Linear**, **Radial**, or **Angular**, a gradient bar appears in the color picker. Each stop on the bar is one color in the gradient. A new gradient has two stops.

* **Change a stop's color**: Select the stop, then choose a color.
* **Add a stop**: Click an empty spot on the gradient bar.
* **Remove a stop**: Select the stop and press Delete or Backspace .
* **Move a stop**: Drag it along the bar.


Gradient stops can also be [keyed on a timeline](/docs/editor/animate-mode/keys) and [bound to data](/docs/editor/data-binding/overview).
### Positioning a gradient
While the color picker is open, the gradient's handles appear on the stage. Drag them to set where the gradient starts and ends. For a radial gradient, the start is the center and the end sets how far the gradient reaches. You can also type exact start and end positions in the color picker.
The start and end handles are also the gradient's first and last color stops. Click one to select that stop and change its color. On a radial gradient, the end handle is the **Gradient Radius**: drag it to set how far the gradient reaches from its center.
### Angular gradients
An angular gradient sweeps its colors around a center point, starting at its rotation angle and going clockwise. It has no start and end. Instead, the color picker shows its **Angular Gradient Transform**:
* **Center**: Where the sweep is centered.
* **Rotation**: Where the sweep starts.
* **Scale**: Stretches the sweep along its X and Y axes.
While the color picker is open, the gradient appears on the stage as a ring around its center, with its color stops just outside the ring:
* **Gradient stops**: Drag a stop around the ring to change where its color sits in the sweep. Click a stop to select it and change its color, or press Delete to remove it.
* **Center handle**: Drag to move the gradient.
* **Rotation and X Scale handle**: Drag around the center to rotate the gradient, or toward and away from the center to scale it along its X axis.
* **Y Scale handle**: Drag toward or away from the center to scale the gradient along its Y axis.
## Image and artboard paints
Set the paint type to **Image** or **Artboard** to paint with an image asset or a component artboard instead of a color. Both work on fills and strokes.
* **Source**: The image asset or artboard to paint with. Image sources can be [bound to data](/docs/editor/data-binding/overview). For **Artboard**, only [component](/docs/editor/fundamentals/components) artboards are listed, and artboards that would end up nested inside themselves are left out.
* **Size**: The size of one image tile.
* **Fill** stretches the image across the shape's bounds.
* **Original** uses the image's pixel size, or the artboard's own size.
* **Filter**: How the image is sampled when it's scaled.
* **Inherit** uses the image asset's setting.
* **Bilinear** is smooth.
* **Nearest** keeps hard pixel edges, which is good for pixel art.
* **Wrap X** and **Wrap Y**: What fills the shape past the image's edges, horizontally and vertically.
* **Inherit** uses the image asset's setting.
* **Clamp** stretches the edge pixels.
* **Repeat** tiles the image.
* **Mirror** tiles the image, flipping every other copy.
* **Scale**: Scales the image relative to its **Size**. With **Repeat** or **Mirror** wrap, a scale below 1 tiles the image across the shape.
* **Offset**: Pans the image, measured in tiles. An offset of 1 moves it one full tile, so animating the offset scrolls a repeating pattern.
* **Rotation**: Rotates the image around the center of the shape's bounds.
### Modulate Image
By default, the image draws as authored. Turn on **Modulate Image** to multiply it by a color or gradient. The color picker then shows its usual controls below the switch, so you can tint the image with a solid color or fade it with a gradient.
## Selected Colors
When you select one or more objects, the **Selected Colors** section of the Inspector lists the colors they use. Use it to see and edit every color in a selection in one place.
# Components
Source: https://rive.app/docs/editor/fundamentals/components
Create reusable artboards that can be instanced throughout your Rive files.
Components are reusable artboards. Create a component once, then use customized instances of it throughout your Rive file. Changes made to the source component are reflected across all of its instances.
You can use components in several ways:
* Place a component inside another artboard as a nested component.
* Reference a component from a [View Model property](/docs/editor/data-binding/property-types#view-model), allowing you to swap them at runtime.
* [Instantiate components from scripts](/docs/scripting/protocols/node-scripts#instantiating-components).
* Use components as items in [Lists](/docs/editor/data-binding/lists).
Components can include their own graphics, animations, state machines, and data, allowing you to build complex experiences from smaller, reusable pieces.
[YouTube video player](https://www.youtube.com/embed/HRUr9mnh41A)
## Creating a component
### Converting Artboards to components
Any artboard can be converted into a reusable component.
**Step 1**
Select an artboard.
**Step 2**
In the Inspector, select the **Component** icon or press `Shift` + `N`.
You can identify components by their purple artboard title on the stage.

> [!NOTE]
>
> Artboards that aren't components aren't exported with your Rive file. This can be useful for artboards used only while authoring, such as tests or reference artboards.
### Converting objects to components
You can select one or more objects on an artboard and convert them into a new component.
**Step 1**
Select the object or objects you want to convert.
**Step 2**
Right-click the selection and select **Create Component**.
Rive creates a new component containing the selected objects and replaces the original selection with an instance of that component.

**Animations and State Machines**
If the selected objects are animated by a timeline on the original artboard, the relevant keys are removed from that timeline and copied to a new timeline inside the component.
State machines aren't copied to the new component. State machines can depend on objects, animations, data, and other elements outside the selection, so you'll need to create a new state machine inside the component.
Data bindings are copied to the new component, but their view models are not.
#### Troubleshooting
Components are self-contained, so Rive can't create a component if the selection depends on objects outside of it. Make sure you include any required dependencies in your selection.
For example, a draw order dependency that crosses the new component's boundary will prevent the component from being created and display the **"Can't create component"** error: **"These dependencies point across the new component's boundary and would break."**

## Placing components
Use the **Component Tool**, formerly known as the Nested Artboard Tool, to place instances of components on the stage. Select the tool from the toolbar or press `N`.
Click anywhere on the stage to choose from the available components and place an instance at that location.

> [!NOTE]
>
> If an artboard doesn't appear in the component menu, make sure you've [converted it to a component](#converting-artboards-to-components).
Alternatively, use the dropdown next to the **Component Tool** to choose a component before placing it.

To place an instance before you've picked a component, select **Create Placeholder** from the component menu. Your next click on the stage places an empty component instance. Set its [Source](#source) later.
The component menu follows the sort mode used in the Assets panel:
* **Custom** displays components as they're organized in the Assets panel.
* **Source/Type** groups components by their source. This is particularly useful when working with [Libraries](/docs/editor/libraries).

### Generating an Artboard
To get a new Artboard with an instance of a component already inside it, right-click the component in the **Assets** panel and select **Generate Artboard**.
## Editing components
Double-click a component instance to open its source component. Changes you make to the source component are reflected in all of its instances, while properties configured on individual instances remain unchanged.

## Bitmap cache
A bitmap cache draws a component's instances from a cached image instead of redrawing their vectors. Use it for components with complex vectors that don't change.
Any change to the component's contents forces the image to redraw, so a cache helps most with static content.
To add a bitmap cache, select the component's artboard and click **+** next to **Bitmap Cache** in the Inspector. The cache applies to every instance of the component. To remove it, click the delete button next to **Bitmap Cache**.
* **Resolution** sets how sharp the cached image is, as a multiple of the size the component is drawn at on screen. `1x` is the default, and `2x` doubles each dimension, using approximately four times as many pixels before the size cap. Higher values look crisper but use more memory. The image is capped at 2048 pixels per side.
* **On / Off** turns the cache on or off without removing it. You can key or data bind it, for example to cache only while the component isn't changing.
## Component instance properties
Select a component instance to configure its properties in the Inspector. These properties control the data, animation, source, layout, and other behavior of that specific instance without changing the source component.

### Origin override
By default, a component instance uses the origin set on its component's artboard. To give one instance a different origin, click **+** next to **Position** in the instance's **Transform** section.
An **Origin** row appears below **Position**, starting at the artboard's current origin. Set **X** and **Y** as a percentage of the instance's size:
* `0%` is the left or top edge.
* `50%` is the center.
* `100%` is the right or bottom edge.
Click **-** next to **Origin** to remove the override and go back to the artboard's origin.
### Source
**Source** determines which component is displayed by the instance. Select a component directly, or data bind the source to change the component dynamically.
A placeholder instance, created with **Create Placeholder** in the component menu, starts with no source. Choose a component or data bind the source to fill it.
Learn more about [Data Binding](/docs/editor/data-binding).
### Data
Configure the data used by a component instance.
**Stateful Components**
If the component is a [Stateful Component](/docs/editor/data-binding/stateful-components), you can set its exposed properties directly on the component instance.
**Model**
Use **Model** to set the view model instance used by the component.
* **Inherit** uses a compatible view model instance from the closest parent.
* To specify an instance, add a **View Model** property to the parent's view model and assign an instance to it. You can then select that property as the component's **Model**.
Learn more about [View Models and Instances](/docs/editor/data-binding/view-models).
### Mode
**Mode** determines how the component instance sizes and responds to the space available from its parent. See [Component Sizing](/docs/editor/layouts/component-sizing) for more information about sizing modes and their properties.
### Deform
A component instance with **Mode** set to **Node** can take a [Mesh](/docs/editor/manipulating-shapes/meshes) or an [N-Slice](/docs/editor/layouts/n-slicing), the same way an image can. Use this to bind a component to bones, animate its vertices, or slice it.
### Animations
Choose the animations that play on a component instance. In most cases, you'll want to select a state machine, but you can also add one or more timeline animations.
**State Machine**
Select a state machine to run on the component instance. You can adjust its playback **Speed** and enable **Quantize**.
**Timeline Animations**
Add timeline animations to play on their own, alongside a state machine, or layered with other animations. When adding a timeline animation, choose between **Simple** and **Remap**.
**Simple** plays the timeline normally and provides the following controls:
* **Mix** controls how much the animation contributes when mixed with other animations.
* **Speed** controls the animation's playback speed.
* **Playing** controls whether the animation is playing.
**Remap** lets you control the position of the animation's playhead directly:
* **Mix** controls how much the animation contributes when mixed with other animations.
* **Time** controls the animation's playhead as a percentage, where `0%` is the beginning and `100%` is the end.
# Design and Animate Modes
Source: https://rive.app/docs/editor/fundamentals/design-vs-animate-mode
Understand when changes edit your design and when they create animation keys.
Rive has two main editing modes: **Design** and **Animate**.
* **Design Mode** is for creating, editing, importing, and rigging objects.
* **Animate Mode** is for creating timelines, state machines, keys, and animation logic.
Use the **Mode Toggle** in the toolbar, or press `Tab`, to switch between modes.

## Avoiding accidental keys
When you're in **Animate Mode**, some edits can create animation keys depending on what is selected.
If a **timeline** is selected, changes to animatable properties may be keyed automatically. This can happen when you move, resize, rotate, recolor, or otherwise edit an object while working in a timeline.
> [!WARNING]
>
> Before making design changes, make sure you're in **Design Mode**, or make sure a timeline is not selected.
## When to use Design Mode
Use **Design Mode** when you want to change the default design of your file.
Common design changes include:
* Creating or deleting objects
* Moving, resizing, or rotating objects
* Editing fills, strokes, and shape properties
* Importing assets
* Adding bones, constraints, or other rigging
## When to use Animate Mode
Use **Animate Mode** when you want to create animation behavior.

Common animation tasks include:
* Creating timelines
* Creating state machines
* Adding keys
* Editing key values
* Setting up transitions, listeners, and animation logic
# Edit Vertices
Source: https://rive.app/docs/editor/fundamentals/edit-vertices
Move vertices, change their bezier handles, and open, reverse, or simplify a path.
Every [path](/docs/editor/fundamentals/shapes-and-paths-overview) is made of vertices. Edit Vertices mode lets you move each vertex, change the curve between vertices with bezier handles, and change the path as a whole. You can edit vertices in Design mode, or in Animate mode to key them.
## Editing vertices
**Step 1**
Enter Edit Vertices mode in any of these ways:
* Select a path and press `Enter`. With a shape selected, press `Enter` twice.
* Double-click a path on the stage. If it's inside a shape, double-click the shape first.
* Click **Edit Vertices** in the **Deform** section of the Inspector.
**Step 2**
Select a vertex and drag it, or drag its bezier handles. Shift-click or drag a selection box to select several vertices.
**Step 3**
To finish, click **Done Editing** in the Inspector or double-click an empty area of the stage.
Paths drawn with a [Shape tool](/docs/editor/fundamentals/procedural-shapes) have no vertices to edit until you convert them to custom paths. When you enter Edit Vertices mode on one, Rive asks you to convert it. Converting removes its procedural properties, such as width, height, and number of points, along with any keys on them.
To add or delete vertices, use the [Pen Tool](/docs/editor/fundamentals/pen-tool-overview#adding-vertices-to-a-path).
> [!TIP]
>
> Use [Deep Select](/docs/editor/interface-overview/selection-and-navigation#deep-select) to select a path inside nested groups on the stage.
## Vertex types
Select one or more vertices to change their type at the top of the vertex properties in the Inspector. The type decides how the vertex's bezier handles behave.
| Type | Handles |
| - | - |
| **Straight** | No handles. The segments on each side are straight lines, and you can round the corner with **Corner**. |
| **Mirrored** | The two handles share the same angle and length. This is the default when you click and drag with the Pen Tool. |
| **Detached** | Each handle has its own angle and length. |
| **Asymmetric** | The two handles share the same angle, but each has its own length. |
To switch types without the Inspector, see the [Pen Tool shortcuts](/docs/editor/fundamentals/pen-tool-overview#path-and-vertex-shortcuts).



### Vertex properties
* **Position**: The vertex's X and Y position.
* **Corner**: The corner radius of a Straight vertex.
* **Bezier**: The angle and length of the handles. Mirrored vertices have one angle and length, Asymmetric vertices have an angle with separate in and out lengths, and Detached vertices have an angle and length for each handle.
## Path options
The path options at the top of the Inspector apply to the whole path.
* **Done Editing**: Exits Edit Vertices mode.
* **Open Path** / **Close Path**: Disconnects the last vertex from the first, or connects them.
* **Reverse Direction**: Reverses the order of the vertices. The direction of a path decides how it's filled when it overlaps other paths in its shape. See [Fill rules](/docs/editor/fundamentals/fill-and-stroke#fill-rules).
* **Convert Radial Corners**: Replaces rounded corners with real vertices. See [Convert Radial Corners](#convert-radial-corners).
* **Simplify**: Reduces the number of vertices. See [Simplify](#simplify).
* **Key All Vertices** and **Key Selected Vertices**: In Animate mode, key every vertex in the path, or only the selected vertices. Press `Shift + K` to key all vertices.
This video shows how reversing a path's direction changes its fill:
[YouTube video player](https://www.youtube.com/embed/zp2NNsSTfO8)
### First vertex
To choose where a path starts, right-click a vertex while editing vertices and select **Make First Vertex**. The other vertices keep their order. On an open path, this also moves the gap between the last vertex and the first.
### Convert Radial Corners
A rounded corner on a Straight vertex is calculated from its **Corner** value, so it stretches when you scale the path or shape unevenly. **Convert Radial Corners** replaces each rounded corner with two curved vertices, so it scales like the rest of the path.
It converts the selected vertices, or every vertex in the path if none are selected.

### Simplify
Use **Simplify** to reduce the number of vertices in a path while keeping its overall shape. It's useful for paths drawn with the [Pencil](/docs/editor/design/freehand-drawing) or imported from an [SVG](/docs/editor/assets/svg).
* **Tolerance**: How far the simplified path can move from the original. Higher values remove more vertices.
* **Corner Angle**: Vertices that turn at least this much are kept as corners. Rounded corners and the vertices next to them are always kept.
* **Straight Lines**: Removes curve handles and corner radii, so only straight segments remain.
The stage previews the result, and the Inspector shows the number of vertices before and after. Click **Simplify Path** to apply it, or select vertices first and click **Simplify Selected** to simplify only those.
Simplify only works in Design mode. If a removed vertex has keys, its keys are removed too, and if the path is bound to bones, the removed vertices' weights are removed.
# Fill and Stroke
Source: https://rive.app/docs/editor/fundamentals/fill-and-stroke
Paint shapes with fills and strokes, and set fill rules, stroke caps and joins, blend modes, and effects.
Fills and strokes are the paint on a [shape](/docs/editor/fundamentals/shapes-and-paths-overview). A fill colors the area inside the shape's paths, and a stroke draws a line along them. A shape can have any number of fills and strokes, and each one applies to every path in the shape.
Fills and strokes are listed in the **Fills and Strokes** section of the Inspector. On a [Layout](/docs/editor/layouts/layouts-overview), the same section is called **Background**, or **Foreground** for a Layout's foreground.
[YouTube video player](https://www.youtube.com/embed/4ZRzKScvJbQ)
## Adding a fill or stroke
**Step 1**
Select a shape.
**Step 2**
In the **Fills and Strokes** section of the Inspector, click **+** and select **Fill** or **Stroke**.

A fill's swatch is a filled square, and a stroke's swatch is an outlined square. A new fill on a shape starts as a gradient, and a new stroke starts as a solid color.

To change a fill or stroke's color or switch it to a gradient, click its swatch. See [Color and Gradients](/docs/editor/fundamentals/color-and-gradients).
## Managing fills and strokes
* **Reorder**: Drag a fill or stroke by an empty area of its row. Items higher in the list draw in front of items lower in the list.
* **Hide**: Click the eye icon. The fill or stroke stays on the shape, but doesn't draw.
* **Delete**: Click the minus icon.
* **Duplicate, copy, or convert**: Right-click a fill or stroke to duplicate or copy it, or to convert a fill to a stroke and a stroke to a fill.


## Fill options
Click the options button on a fill to open its options.

* **Name**: The fill's name.
* **Blend**: The fill's [blend mode](#blend-modes).
* **Fill Rule**: How overlapping paths are filled. See [Fill rules](#fill-rules).
* **Feather**: Softens the fill's edge. See [Vector Feathering](/docs/editor/fundamentals/vector-feathering).
The **Effects** tab adds path effects, such as a trim or dash, to the fill. See [Path effects](#path-effects).
### Fill rules
When a shape has more than one path, or a path crosses itself, the fill rule decides which areas are inside the shape and get filled. To cut a hole in a shape, put the hole's path inside the shape's outer path and choose a fill rule that leaves the overlap empty.
* **Non-zero** is the default. Each path counts +1 if it's drawn clockwise and −1 if it's drawn counter-clockwise. Areas where the total isn't zero are filled. Two overlapping paths drawn in the same direction fill the overlap, and two drawn in opposite directions leave it empty.
* **Even-odd** ignores direction and counts how many paths surround an area. Areas inside an odd number of paths are filled, and areas inside an even number are empty. A path inside another path always makes a hole.
* **Clockwise** is a fill rule made by Rive. Paths drawn clockwise fill, and paths drawn counter-clockwise cut away from them, so you can subtract one path from another by reversing its direction. Feathered fills always use Clockwise.
To change a path's direction, use **Reverse Direction** while [editing its vertices](/docs/editor/fundamentals/edit-vertices).
## Stroke options
Set a stroke's thickness in the field on its row. Click the options button on a stroke to open the rest of its options.
* **Name**: The stroke's name.
* **Blend**: The stroke's [blend mode](#blend-modes).
* **Position**: Where the stroke sits on the path: **Inside**, **Center** (the default), or **Outside**. Inside and outside strokes treat the path as closed.
* **Cap**: How the ends of an open path look. Only centered strokes have caps.
* **Butt** ends the stroke flat at the end point. A path with no length doesn't draw.
* **Round** adds a rounded end. A path with no length draws a circle.
* **Square** adds a square end that extends past the end point. A path with no length draws a square.
* **Join**: How corners look: **Round**, **Bevel**, or **Miter**.
* **Apply transform**: When it's on, scaling the shape also scales the stroke's thickness. Turn it off to keep the thickness the same at any scale.
* **Feather**: Softens the stroke's edge. See [Vector Feathering](/docs/editor/fundamentals/vector-feathering).
The **Effects** tab adds path effects to the stroke. See [Path effects](#path-effects).
## Blend modes
Each fill and stroke has its own blend mode. By default it's set to inherit the shape's blend mode.
### Additive
When a fill, stroke, or object uses the **Normal** blend mode, an **Additive strength** field appears below it. It sets how much the paint adds light to what's behind it, from normal blending at 0% to fully additive blending at 100%. Use it for glows and light effects. Click the slider icon next to the field to show or hide its slider.
Additive strength can be keyed on a timeline and [bound to data](/docs/editor/data-binding/overview).
> [!NOTE]
>
> Partial additive strength, between 0% and 100%, requires the Rive Renderer. See [Choosing a Renderer](/docs/runtimes/choose-a-renderer/overview).
## Path effects
Path effects change the path a fill or stroke draws, without changing the shape itself. Add them from the **Effects** tab of a fill or stroke's options:
* **Trim Effect** draws only part of the path, so you can animate a line drawing on. See [Trim and Dash](/docs/editor/manipulating-shapes/trim-path).
* **Dash Effect** breaks the path into dashes and gaps. See [Trim and Dash](/docs/editor/manipulating-shapes/trim-path#dash).
* **Effect Group** applies a shared stack of effects that you control in one place. See [Effect Groups](/docs/editor/manipulating-shapes/effect-groups).
* **Scripted path effects** apply a [path effect script](/docs/scripting/protocols/path-effect-scripts).
## Vector Feathering
To soften the edge of a fill or stroke, for glows, drop shadows, and inner shadows, use [Vector Feathering](/docs/editor/fundamentals/vector-feathering).
## Effect Groups
To share the same trim, dash, or scripted effects across many fills and strokes, and control them from one place, use an [Effect Group](/docs/editor/manipulating-shapes/effect-groups).
# Groups
Source: https://rive.app/docs/editor/fundamentals/groups
Use groups to organize objects, and to add pivots so you can animate objects from more than one point.
A group is an empty container. It isn't drawn, but its children inherit its position, rotation, and scale, like any other parent in the [Hierarchy](/docs/editor/interface-overview/hierarchy#parent-child-relationships). Use groups to:
* **Organize** related objects, so you can select, move, and hide them together.
* **Add a pivot**, so you can rotate or scale objects from a point other than their own origin. See [Using groups as pivots](#using-groups-as-pivots).
* **Mark a point** for a [constraint](/docs/editor/constraints/constraints-overview) or other feature to target. See [Target style](#target-style).
## Creating a group
* **From a selection**: Select objects and press `Cmd + G` (macOS) or `Ctrl + G` (Windows).
* **With the Group tool**: Press `G`, click the artboard to add an empty group, then drag objects into it in the Hierarchy.
To remove a group and keep its children, select it and press `Cmd + Shift + G` (macOS) or `Ctrl + Shift + G` (Windows). You can also right-click the group in the Hierarchy and select **Ungroup**.
## Using groups as pivots
Each object rotates and scales around its own origin. Nesting it in a group adds a second origin, and the group's rotation and scale move the object around that point. Nest more groups to add more pivots, and animate each one separately. In motion graphics this is often called a transform space.
For example, a moon can spin on its own axis while it orbits the Earth:
* An **Earth** group rotates the Earth.
* A **Moon** group sits at the Earth's center and rotates, carrying the moon around the Earth.
* Inside it, a group at the moon's center rotates the moon on its own axis.


To change where a group rotates and scales from without moving its children, use [Freeze](/docs/editor/fundamentals/origin#freeze).
[YouTube video player](https://www.youtube.com/embed/IcSXchdnzHM)
## Target style
Set a group's **Style** in the Inspector to choose how it appears on the stage.
* **Group** is the default. A group only shows an icon on the stage when it's empty.
* The **Target** styles always show an icon on the stage, even when the group has children. Choose a circle, square, or triangle, at full or small size.
Targets are directly selectable on the stage without [Deep Select](/docs/editor/interface-overview/selection-and-navigation#deep-select). This makes them useful as handles for [constraints](/docs/editor/constraints/constraints-overview), such as an IK target for a foot. The style only affects the editor.

> [!TIP]
>
> If targets aren't visible on the stage, open the **View Options** menu and make sure **Targets** is enabled.
# Origin
Source: https://rive.app/docs/editor/fundamentals/origin
Change the point an object rotates and scales from, with Freeze, the align tools, or the Origin property.
An object's origin is the point it rotates and scales from, sometimes called its pivot or anchor point. Its children rotate and scale around it too. The origin changes how an animation looks: a door swings from its hinge, not its middle, and a bar grows from one end, not its center.
[YouTube video player](https://www.youtube.com/embed/nA15ZXkMb_c)
You can move an origin in three ways:
* **[Freeze](#freeze)**: Drag the origin of any object on the stage.
* **[Align tools](#with-the-align-tools)**: Snap the origin to an edge or the center of the object.
* **[Origin property](#origin-of-a-shape)**: Set an exact position for shapes drawn with the Shape tools.
## Freeze
Moving a parent normally moves its children with it. Freeze lets you move a parent, such as a group, shape, or bone, without moving its children, so you can put its origin anywhere.
**Step 1**
Press `Y`, or select **Freeze** from the **Transform Tools** menu in the [toolbar](/docs/editor/interface-overview/toolbar).
**Step 2**
Select the object and move it to where you want its origin. Its children stay in place.
**Step 3**
Press `Y` again to turn off Freeze.
While Freeze is on, the stage is outlined in blue as a reminder. Remember to turn it off, or the next objects you move will leave their children behind too.
## With the align tools
Hold `Alt` (Windows) or `Option` (macOS) with an object selected, and the [align buttons](/docs/editor/fundamentals/align-and-distribute) set its origin instead of moving it. Choose left, center, right, top, middle, or bottom of the object's bounds.
You can also use these shortcuts:
| Shortcut | Origin |
| - | - |
| `Alt + A` / `Alt + D` | Left / right |
| `Alt + W` / `Alt + S` | Top / bottom |
| `Alt + H` | Horizontal center |
| `Alt + V` | Vertical middle |
## Origin of a shape
Shapes drawn with the [Shape tools](/docs/editor/fundamentals/procedural-shapes) have an **Origin** property in the Inspector, set as a percentage of the shape's size. It also decides which way the shape grows when you change its size.
With the origin at 50% X and 50% Y, changing the width grows the rectangle from its center:

With the origin at 0% X, the rectangle grows from its left edge:

Artboards also have an Origin property. See [Artboards](/docs/editor/fundamentals/artboards).
# Pen Tool
Source: https://rive.app/docs/editor/fundamentals/pen-tool-overview
Draw custom vector paths and add vertices to existing paths.
[YouTube video player](https://www.youtube.com/embed/dE1OEaaX5dw)
Use the **Pen Tool** to draw custom vector paths one vertex at a time. It gives you precise control over every point and curve.
> [!TIP]
>
> For common shapes such as rectangles and ellipses, use the [Shape tools](/docs/editor/fundamentals/procedural-shapes) instead. To draw freehand, use the [Pencil](/docs/editor/design/freehand-drawing).
## Drawing a path
**Step 1**
Select the **Pen Tool** from the Create Tools menu, or press P .
**Step 2**
Click the stage to place straight vertices. Click and drag to place a vertex with mirrored bezier handles.
**Step 3**
Click the first vertex to close the path, or press Esc to finish with an open path.


> [!TIP]
>
> While dragging out a new vertex, hold Alt /Opt to detach its handles. This lets you make a sharp change of direction between two curves.
To keep drawing an open path later, select it, press Enter to edit its vertices, then click its last vertex with the Pen Tool. To open a closed path, use **Open Path** in [Edit Vertices](/docs/editor/fundamentals/edit-vertices).
## Adding vertices to a path
With the Pen Tool active, move the pointer over a segment of a path you're editing. The pointer snaps to the segment, and a click splits it with a new vertex at that point. Drag right after clicking to move the new vertex.
## Path and vertex shortcuts
These shortcuts work with the Pen Tool. Shortcuts marked "Pen or Select" also work with the Select tool while you edit vertices.
| Shortcut | Target | Tool | Result |
| - | - | - | - |
| Cmd /Ctrl + click | Vertex | Pen or Select | Toggle between straight and mirrored handles |
| Cmd /Ctrl + drag | Vertex | Pen or Select | Pull out mirrored bezier handles |
| Cmd /Ctrl + click | Handle | Pen or Select | Remove the handle |
| Alt /Opt + click | Handle | Pen or Select | Detach the handle from its partner |
| Alt /Opt or Cmd /Ctrl + drag | Handle | Pen or Select | Detach the handle and drag it freely |
| Alt /Opt + click | Vertex | Pen | Delete the vertex |
To learn more about straight, mirrored, and detached handles, and the other path options, see [Edit Vertices](/docs/editor/fundamentals/edit-vertices).
# Shape Tools
Source: https://rive.app/docs/editor/fundamentals/procedural-shapes
Create editable shapes with adjustable properties.
Shape tools let you create common shapes, such as rectangles, ellipses, triangles, polygons, and stars. These shapes keep editable properties, such as width, height, corner radius, and number of points, until you convert them to custom paths.
[YouTube video player](https://www.youtube.com/embed/vU5SrgymGD8)
## Creating a shape
Shape tools are available from the **Create Tools** menu.
**Step 1**
Open the **Create Tools** menu and select a shape tool.
**Step 2**
Click and drag inside an artboard to draw the shape.
Hold `Shift` while dragging to constrain the shape's proportions.
> [!NOTE]
>
> See [Origin](/docs/editor/fundamentals/origin) to learn how to change the point a shape rotates and scales from.
## Shape properties
You can update a shape's properties in its **Path** section of the inspector, such as **Rectangle Path** or **Star Path**. Available properties depend on the selected shape type.
* **Size**: The width and height of the shape.
* **Origin**: The [origin](/docs/editor/fundamentals/origin) point of the shape.
* [Corner](#corner): The corner radius of rectangles.
* [Radius](#radius): The radius of polygons and stars.
* [Points](#points): The number of points on polygons and stars.
* [Inner radius](#inner-radius): How deep a star's inner points go, as a percentage of its size.
### Corner
Adjust the corner radius by dragging the circular handles on each corner of the rectangle.
Hold `Alt` (Windows) or `Option` (macOS) while dragging to adjust a single corner independently.

### Radius
Drag the radius handle to adjust the radius of all points on the shape at once.

### Points
Control the number of points by dragging the points handle up or down.

### Inner radius
Drag the handle on the star's inner point toward or away from the center to move the inner points. Moving them in makes the points sharper, and moving them out makes them blunter. Hold `Shift` to snap to 5% steps.
You can also type the inner radius in the second **Radius** field in the inspector.

## Converting a shape to a custom path
Press `Enter` to convert the selected shape to a path. After conversion, you can edit each vertex directly.
> [!NOTE]
>
> Converting a shape to a path removes its procedural properties, such as width, height, corner radius, and number of points. Any animations applied to those properties are also removed.
> [!NOTE]
>
> To edit a path, see [Edit Vertices](/docs/editor/fundamentals/edit-vertices).
# Revision History
Source: https://rive.app/docs/editor/fundamentals/revision-history
Browse, name, preview, and restore earlier versions of a file.
Rive saves your work automatically as you edit, including when several people edit the same file at once. These saves are stored in the file's Revision History, so you can look back at earlier versions of a file and restore one if you need to.
Revision History holds two kinds of revisions:
* **Autosaves** are created automatically as you work.
* **Named revisions** are checkpoints you create yourself, such as "Before rig rework" or "Sent to client". They're easier to find later.
> [!NOTE]
>
> Revision History is available on paid plans. [Learn more about our plans and pricing](https://rive.app/pricing?utm_source=docs\&utm_medium=content).
## Viewing a file's history
Open the [Editor Menu](/docs/editor/interface-overview/toolbar) and select **Revision History**. The current version appears at the top of the panel, with earlier revisions grouped by day below it.

To show only named revisions, open the panel's options menu and turn off **Show Autosave Revisions**. Use **Collapse All** and **Expand All** in the same menu to fold or unfold the day groups.
## Restoring a revision
**Step 1**
In **Revision History**, click a revision to preview it on the stage.
**Step 2**
Click **Restore** at the top of the editor, or right-click the revision and select **Restore Revision**.

The restored revision becomes the current version of the file. The other revisions stay in the history, so you can restore a different one if you change your mind.
## Creating a named revision
**Step 1**
Open the Editor Menu and select **Create revision...**, or click **+** in the **Revision History** panel.
**Step 2**
Enter a name for the revision and click **Save**.

To name an autosave, or to rename a named revision, right-click it in **Revision History** and select **Name revision** or **Rename revision**.
## Downloading a revision
To download an earlier revision without opening the file, right-click the file in the [File Browser](/docs/editor/interface-overview/file-browser), open **Download Revision**, and select a revision.
# Shapes and Paths
Source: https://rive.app/docs/editor/fundamentals/shapes-and-paths-overview
How shapes and paths work together: shapes hold the fills and strokes, and paths define the geometry.
Every vector in Rive is made of two parts:
* A **shape** decides how the vector looks. It holds the [fills and strokes](/docs/editor/fundamentals/fill-and-stroke).
* One or more **paths** inside the shape decide its geometry.
The shape paints every path inside it, so all of its paths share the same fills and strokes. To give part of a drawing a different color, put that part in its own shape.
[YouTube video player](https://www.youtube.com/embed/KunkCnbkTsg)
## Shapes
When you draw with a [Shape tool](/docs/editor/fundamentals/procedural-shapes), the [Pen Tool](/docs/editor/fundamentals/pen-tool-overview), or the [Pencil](/docs/editor/design/freehand-drawing), Rive creates a shape with a path inside it. In the Hierarchy you see the shape, and its paths are nested under it.
Select the shape to edit its fills and strokes in the Inspector. Moving, rotating, or scaling the shape transforms all of its paths together.

## Paths
Expand a shape in the Hierarchy to see its paths. Select a path to move, rotate, or scale it on its own, without changing the rest of the shape.

A path is one of two kinds:
* **Procedural paths** come from the [Shape tools](/docs/editor/fundamentals/procedural-shapes), such as rectangles, ellipses, polygons, and stars. They keep properties like size, corner radius, and number of points, which you can change and animate in the Inspector.
* **Custom paths** are drawn vertex by vertex with the [Pen Tool](/docs/editor/fundamentals/pen-tool-overview), or freehand with the [Pencil](/docs/editor/design/freehand-drawing). You shape them by [editing their vertices](/docs/editor/fundamentals/edit-vertices).

To edit the vertices of a procedural path, it has to become a custom path. When you start editing its vertices, Rive asks you to convert it. Converting removes its procedural properties, along with any keys on them.
## Combining paths in a shape
A shape can hold any number of paths. To add a path to a shape, drag it onto the shape in the Hierarchy. The path takes on that shape's fills and strokes.

With a path selected, the Pen Tool also adds new paths to that path's shape instead of creating a new one.
Where a shape's paths overlap, its [fill rule](/docs/editor/fundamentals/fill-and-stroke#fill-rules) decides which areas are filled, so you can use one path to cut a hole in another.
## Path length
When you select a shape, the Inspector shows its **Length**: the total length of all of its paths. Length is read-only, so you can't type a value, but you can bind other properties to it. For example, bind the size of text that [follows the path](/docs/editor/text/text-modifiers#follow-path) so it always fits the path's length.
## Moving between shapes and paths
* Press `Enter` with a shape selected to select its first path.
* Press `Esc` with a path selected to select its shape.
Pressing `Enter` with a path selected [edits its vertices](/docs/editor/fundamentals/edit-vertices).
# Vector Feathering
Source: https://rive.app/docs/editor/fundamentals/vector-feathering
Soften the edges of fills and strokes to create glows, drop shadows, inner shadows, and soft shapes.
Vector Feathering softens the edge of a fill or stroke, so it fades out gradually instead of ending in a hard line. Use it for glows, drop shadows, inner shadows, soft light, and any shape that needs a blurred edge.
Rive invented Vector Feathering. It softens the vector path itself instead of blurring rendered pixels, which avoids the heavy cost of a traditional Gaussian blur and keeps the edge crisp at any size. To learn how it works and why it's so much faster, read [How Rive reinvented feathering for the vectorian era](https://rive.app/blog/how-rive-reinvented-feathering-for-the-vectorian-era?utm_source=docs\&utm_medium=content).
> [!NOTE]
>
> Vector Feathering requires the Rive Renderer. Runtimes or packages that draw with another renderer, such as the web runtime's Canvas2D packages, don't support it. See [Choosing a Renderer](/docs/runtimes/choose-a-renderer/overview).
## Adding a feather
You can feather any fill or stroke.
**Step 1**
Select the shape.
**Step 2**
In the Inspector, click the feather icon on the fill or stroke you want to soften. You can also turn on **Feather** in the fill or stroke options.

**Step 3**
Open the fill or stroke options to adjust the feather.
To remove a feather, click the feather icon again. Rive keeps the feather's settings, so turning it back on restores them.
> [!WARNING]
>
> Feathering a fill switches it to Rive's Clockwise fill rule, and you can't change the fill rule while the feather is on. Self-intersecting paths can look different with this fill rule than they did in your original design.
## Feather options
### Direction
Only fills have a direction.
* **Outer** feathers outward from the edge of the path, like a glow or a shadow. This is the default.
* **Inner** feathers inward from the edge, like an inner shadow or a vignette.

### Amount
How soft the edge is. Higher values spread the feather over a wider area. The default is 12.

### Offset
Moves the feather away from the path by an **X** and **Y** distance. Use it to cast a shadow below or to the side of a shape.
### Space
Sets which transform the offset follows.
* **World** keeps the offset pointing the same way, even if the shape or its parents rotate or scale. Use it for drop shadows that should stay consistent with a single light source. This is the default.
* **Local** moves the offset with the shape, so it rotates and scales along with it.

**Direction**, **Amount**, and **Offset** can all be keyed on a timeline or [bound to data](/docs/editor/data-binding/overview).
## Examples
### Glow
**Step 1**
Add a second fill or stroke to the shape and give it a bright color.
**Step 2**
Move it behind the original fill or stroke.
**Step 3**
Turn on its feather and raise the **Amount** until the glow is as wide as you want.
### Drop shadow
**Step 1**
Add a second fill to the shape, give it a dark, semi-transparent color, and move it behind the original fill.
**Step 2**
Turn on its feather and set an **Amount**.
**Step 3**
Set the **Offset** to move the shadow, for example a few units down and to the right.
**Step 4**
Keep **Space** set to **World** so the shadow stays in the same direction as the shape rotates.
### Inner shadow
Add a second fill above the original fill, give it a dark color, then turn on its feather and set **Direction** to **Inner**. Add an **Offset** to push the shadow toward one edge.
# Using the Rive Editor
Source: https://rive.app/docs/editor/get-rive
Choose how you want to use the Rive editor: in your browser or as a desktop app.
To get started, [sign up for a Rive account](https://rive.app/signup/?redirect=%2Faccount%2Fteams%2F\&utm_source=docs\&utm_medium=content).
You can use the Rive editor as a **desktop app** or directly in your [browser](https://editor.rive.app). Both versions provide the same core features and workflows.
> [card] [Desktop Apps](https://rive.app/downloads?utm_source=docs\&utm_medium=content)
>
> Download the Rive editor for macOS or Windows.
> [card] [Early Access](https://rive.app/downloads)
>
> Voyager users can preview upcoming features in the Early Access Editor.
# Debug Panel
Source: https://rive.app/docs/editor/interface-overview/debug-panel
Inspect logs, problems, AI changes, tests, and audio while working in Rive.
The Debug Panel shows output and diagnostic information while you work in Rive. Use it to inspect console logs, find problems, review AI Agent changes, run tests, and preview audio.

## Tabs
The Debug Panel is organized into tabs.
* **Console** - view script logs, runtime errors, and State Machine activity.
* **Problems** - view code issues, broken bindings, validation warnings, and other problems in the file.
* **Changes** - review pending changes from the AI Agent.
* **Testing** - run [test scripts](/docs/scripting/debugging/unit-testing).
* **Audio** - [preview audio assets](/docs/editor/assets/audio#previewing-sounds) and [create clips](/docs/editor/assets/audio#creating-clips).
### Console
The Console shows output from scripts and State Machines.
Use the sidebar in the Console tab to switch between the script console and the State Machine console.
Use the Console options to clear the console, clear the console when playback starts, or copy console output.
#### Script Console
The script console shows output from scripts, including `print()` messages and runtime errors.
See [Script Console](/docs/scripting/debugging/debug-panel#console) for more information.
#### State Machine Console
The State Machine console shows State Machine activity during playback, such as entering a state or taking a transition.

### Problems
The Problems tab lists issues found in the file. These can include code problems, broken data bindings, validation warnings, or problematic State Machine setup.
Errors are indicated by a red dot, while warnings are yellow.
Problems are grouped by artboard, script, or category, and each group shows its error and warning counts. Click the arrow next to a group to expand or collapse it. Clicking an artboard group selects that artboard.
Use the Problems options to filter problems, show or hide warnings, and include non-script validation.
Click a problem to open the affected code line, binding, State Machine item, or related editor location.
See [Script Problems](/docs/editor/interface-overview/debug-panel#problems) for handling script-related problems.
### Changes
The Changes tab shows pending changes from the AI Agent.
Use this tab to review changes before applying them to your file.
Each script with pending changes is listed with its added and removed line counts. Click a script to open it and review the changes. See [Reviewing script changes](/docs/editor/ai-agent/ai-agent#reviewing-script-changes).
# File Browser
Source: https://rive.app/docs/editor/interface-overview/file-browser
Create, organize, and manage files, projects, and workspaces.
The File Browser is where you create, open, organize, and manage your Rive files. You can also browse recent files, open Marketplace examples, switch between workspaces, and manage projects.
[YouTube video player](https://www.youtube.com/embed/m8WNIVeMOpk)
## Home
The Home view shows your recent files, links to tutorial videos, and Marketplace examples.

* **Recents** - files you opened recently. **View all** opens the Recents page.
* **Learn Rive** - resources for learning Rive. **View all** opens the full playlist in your browser.
* **Marketplace Examples** - files from the [Rive Marketplace](/docs/community/marketplace-overview) you can open and learn from. **View all** opens the Marketplace in your browser.
* **Announcement** - news from Rive, like new features and events. A dot on **Home** in the sidebar means there is a new announcement.
When you have a file open, click the **Home** tab in the tab bar to return to the File Browser.
## File tabs
Each file you open gets a tab in the tab bar at the top of the window.
* Click a tab to switch to that file. Press Ctrl + Tab or Ctrl + Shift + Tab to go to the next or previous tab.
* Double-click a tab's name to rename the file.
* Drag a tab to reorder it.
* Click the **X** on a tab to close the file.
When the tabs don't fit, a **+** button with a count appears at the end of the tab bar. Click it to see the other open files and pick one to switch to it.
### Tab menu
Right-click a file tab to close several tabs at once:
* **Close Other Tabs**: Close every tab except this one.
* **Close Tabs to the Right** and **Close Tabs to the Left**: Close every tab on that side of this one.
* **Close All Tabs**: Close every file tab.
[Viewport tabs](/docs/editor/interface-overview/stage#viewport-tabs) have the same menu.
## Managing files
Right-click anywhere within the File Browser to create a new file or folder.
Right-click a file to open additional options, including:
* **Open**, **Copy**, **Cut**, **Duplicate**, and **Delete** - common file actions
* **Show File in Browser** - open the file’s location in the File Browser
* **Download** - download the file as a `.riv`
* **Download Backup** - download a `.rev` backup file
* **Download Revision** - download a specific revision
* **Add to Favorites** and **Remove from Favorites** - favorite files show a favorite icon and are listed under **Favorites** in the sidebar
The folder path above the files shows where you are. Click a folder in the path to jump back to it, or drop files on it to move them there.
## Toolbar
The toolbar includes options for managing your account, changing display options, creating folders, and creating new files.
* **Back** and **Forward** - step through the File Browser views you have visited.
* **Navigate to File** - paste a Rive file URL to jump to that file.
* **Notifications** - workspace invites, responses to your invites, and new followers. A red dot means you have unread notifications.
* **Account** - manage your account or sign out.
* **Thumbnail Size** - resize the thumbnails. List and grid views each keep their own size.
* **List** and **Grid** - show items as a list or as a grid of thumbnails. In list view, click a column header to sort by it, and click it again to flip the order.
* **Sort** - order items by last modified, created, or name, ascending or descending. **Group by type** puts folders first. **Group favorites** puts favorite files next.
* **New File Prompt** (sparkle) - when on, **New File** opens a prompt so the [AI Agent](/docs/editor/ai-agent/ai-agent#starting-a-new-file-with-the-agent) can build the file for you. When off, **New File** makes a blank file.
* **New Folder** - create a folder in the current project.
* **New File** - create a Rive file in the current folder.
## Sidebar
Use the sidebar to search files, view recent files, access files shared with you, and navigate between workspaces and projects.
* **Home** - your recent files, tutorial videos, and Marketplace examples.
* **Search** - find files by name, including files shared with you.
* **Recents** - files you opened recently.
* **Favorites** - files you added to your favorites.
* **Shared with me** - files other people have shared with you directly. Each file shows the workspace it belongs to.
* **Tutorials** - video tutorials for learning Rive.
* **Marketplace** - browse files made by the community. Opens in your browser.
* **Community** - ask questions and share work on the [Rive community forum](https://community.rive.app/). Opens in your browser.
### Projects
Projects help you organize files within a workspace.
Use projects to group related files, such as files for a client, feature, campaign, or product area. For example, you might have separate projects for personal work and freelance work.
> [!NOTE]
>
> Projects and folders are available on Cadet, Voyager, and Enterprise plans. [Learn more about our plans and pricing](https://rive.app/pricing?utm_source=docs\&utm_medium=content).
#### Create a new project
**Step 1**
In the sidebar, click **+ Create Project**.
**Step 2**
Add a project name and choose who should have access.

Use **Everyone in Workspace** to set access for all workspace members:
* **Can access** - each person keeps their workspace role.
* **Can view** - everyone is a viewer.
* **No access** - only members you add later.
#### Managing project members
You can invite people to a specific project. This is useful when someone needs access to a set of files, but does not need access to the entire workspace.
**Step 1**
In the sidebar, select a project.
**Step 2**
Expand the project details panel to invite, remove, or change permissions for individual members or groups.

The project details panel shows who can access the project:
* **Project name** - admins can click it to rename the project, set up library sharing, or archive the project.
* **Stats** - editor and viewer counts. These include external members who have access to files in this project.
* **Invite Team Members** - add people who are already in this workspace.
* **Everyone in Workspace** - set access for all workspace members: **Can access** (each person keeps their workspace role), **Can view** (everyone is a viewer), or **No access** (only listed members).
* **Members** - each person's project role: Editor, Admin, or Viewer. **Remove** takes them off the project.
* **External Members** - people outside this workspace who have access to individual files in this project. Admins can remove their access.
Click **Confirm changes** to apply your member changes. If they raise your bill, you'll see the cost and confirm before you're charged. Changes that lower your bill are credited to your account.
#### Archiving a project
Archived projects are hidden from the sidebar. To archive a project, click the project name in the project details panel and choose **Archive project**. To bring one back, open the [workspace admin](/docs/account-admin/workspaces/workspaces-overview#workspace-admin), go to the **Projects** tab, and click **Restore**.
### Workspaces
Workspaces are separate spaces for files, members, and billing. You might have a personal workspace, a company workspace, or separate workspaces for different teams.
See [Workspaces Overview](/docs/account-admin/workspaces/workspaces-overview) for more information.
> [!NOTE]
>
> If you only want to organize files or share a specific set of files, create a project instead of a new workspace.
# Hierarchy
Source: https://rive.app/docs/editor/interface-overview/hierarchy
View, organize, and reorder objects in your file.
[YouTube video player](https://www.youtube.com/embed/FnnZV57Dp3c)
The Hierarchy is a tree view that shows the objects on the stage. It shows both how objects are nested and the order in which they are rendered.
## Renaming items
You can rename items in the Hierarchy to make your file easier to understand and navigate.
To rename an item, double-click its name in the Hierarchy, enter a new name, then press Enter.
## Searching and filtering
Click the search button in the Hierarchy header to filter the Hierarchy by object name.
You can also filter the Hierarchy to one type of object, such as bones or layouts, with **Filter Trees** in the [View Options menu](/docs/editor/interface-overview/stage#object-types). While a type filter is on, a **Filter** chip appears in the Hierarchy header. Click it to clear the filter.
## Parent-child relationships
Each row in the Hierarchy represents an item on the stage. Items with children have a button with an arrow next to them. Use this button to expand or collapse the list of children. Holding Alt/Option and clicking this arrow will deep expand the hierarchy item, revealing all children objects.
Any object can be a parent or child of another object. When an object is nested under another object, it inherits the transformations of its parent.
For example, scaling a parent object also scales its children. Parent transformations are applied from the parent’s origin, not the child’s local origin.
> [!NOTE]
>
> To change where a parent rotates and scales from without moving its children, move its origin with [Freeze](/docs/editor/fundamentals/origin#freeze).
You can nest objects as deeply as needed, creating children, grandchildren, great-grandchildren, and so on. Nesting objects in [groups](/docs/editor/fundamentals/groups#using-groups-as-pivots) lets you rotate and scale them around more than one point.
To change the relationship between objects, drag an item onto another item to make it a child. Drag it out of the parent to remove the relationship.
## Draw Order
The Hierarchy also controls draw order. Objects higher in the Hierarchy render above objects lower in the Hierarchy.
> [!NOTE]
>
> You can override the default draw order with [custom draw order](/docs/editor/animate-mode/animating-draw-order).
To change draw order, drag objects up or down in the Hierarchy.

## Lock, isolate, and hide items
When you hover over an item in the Hierarchy, controls appear for locking, isolating, or hiding that item.
* **Lock** prevents the item from being selected or edited on the stage.
* **Isolate** focuses on the item by temporarily hiding other items from view.
* **Hide** hides the item. Hidden items don't render at runtime either.
These controls also apply to any children nested under the item.
To turn off isolation for every object on the active artboard, click the panel options button in the Hierarchy header and select **Clear Isolates**.
> [!NOTE]
>
> Lock and isolate are editor workflow tools. They do not change the exported file or runtime behavior.
## Context menu
Right-click an item in the Hierarchy to open additional options. Depending on the selected item, options may include:

* Copy, cut, paste, delete, and [copy and paste styles](#copying-and-pasting-styles)
* Expand or collapse nested items
* Show dependencies
* Lock, hide, or isolate elements
* Add a [tag](/docs/editor/tagging)
* Reverse the order of elements
* [Export name](/docs/editor/exporting/exporting-names)
Many of these options are also covered in more detail on related pages.
## Copying and pasting styles
Use **Copy Styles** and **Paste Styles** to give shapes and text the same look.
**1. Copy the styles**
Right-click a shape or text object and select **Copy Styles**, or press `⌘` + `Alt` + `C` on macOS or `Ctrl` + `Alt` + `C` on Windows.
**2. Paste the styles**
Select one or more shapes or text objects, right-click, and select **Paste Styles**, or press `⌘` + `Alt` + `V` on macOS or `Ctrl` + `Alt` + `V` on Windows.
Styles are the object's [fills and strokes](/docs/editor/fundamentals/fill-and-stroke), including their colors, gradients, and effects such as [trim paths](/docs/editor/manipulating-shapes/trim-path), dashes, and [feathering](/docs/editor/fundamentals/vector-feathering). Pasting replaces the existing fills and strokes on the selected objects. When you paste from one shape to another, the blend mode and opacity are copied too, and gradients are scaled to fit the new shape.
> [!NOTE]
>
> You can only copy and paste styles in Design mode, and you can copy from one object at a time.
## Spaces
Spaces group your [artboards](/docs/editor/fundamentals/artboards) in the editor. Each space has its own stage view and [background colors](/docs/editor/interface-overview/stage#stage-background-colors), so you only see the artboards in the space you're working in. Use spaces to keep related artboards together and organize large files.
Spaces only organize your work in the editor. They aren't exported.
### Showing spaces
Click the **Spaces** button in the Hierarchy header to switch the panel to **Spaces**. It lists each space with its artboards. Click the button again to return to the Hierarchy.
* Click a space to bring its stage forward in the viewport.
* Click an artboard to select it. Click the arrow next to it to show its objects in the Hierarchy.
### Creating and managing spaces
To add a space, click the **+** button in the panel header and select **Space**. The new space opens so you can name it. To add an artboard to a space, click the **+** button on the space's row.
* Drag an artboard onto another space to move it, or right-click it and select **Move to**.
* Drag spaces up or down to reorder them.
* Right-click a space to rename, duplicate, or delete it.
When you delete a space that has artboards, the editor asks what to do with them. A file always needs at least one space.
The panel options menu in **Spaces** has **Reset Project Layout**, which resets the sidebar layout.
# Inspector
Source: https://rive.app/docs/editor/interface-overview/inspector
View and edit properties for the current selection.
The Inspector is the right sidebar in the editor. It shows the available properties and options for the current selection.

## Selection properties
When you select an element, the Inspector updates to show controls for that element.
For example, selecting an artboard, object, joystick, script, property group, or State Machine item shows different options based on what that element can do.
## Transform properties
Most objects show a **Transform** section at the top of the Inspector.
* **Position:** the X and Y position, relative to the parent.
* **Scale:** the horizontal and vertical scale, around the object's [origin](/docs/editor/fundamentals/origin). Click the link button to keep X and Y in proportion, so changing one changes the other by the same amount.
* **Rotation:** the rotation in degrees, around the origin.
Because these values are relative to the parent, moving, rotating, or scaling a parent also affects its children. Learn more in [Parent-child relationships](/docs/editor/interface-overview/hierarchy#parent-child-relationships).
## Opacity and visibility
The **Blend** section holds the blend mode, opacity, and visibility of the selection.
* **Opacity** applies to the object and everything inside it.
* The **Visibility** button shows or hides the object and everything inside it. It's the same as **Hide** in the [Hierarchy](/docs/editor/interface-overview/hierarchy#lock-isolate-and-hide-items). Hidden objects don't render at runtime either.
## Computed Transform
The **Computed Transform** section shows where an object ends up after layouts, constraints, and parents are applied. Click the section header to expand it. All values are read-only.
* **World:** the final X and Y relative to the root artboard. At runtime, this includes the offset of any artboards this one is nested in.
* **Artboard:** the final X and Y relative to the artboard the object is in.
* **Local:** the final X and Y relative to the parent, after layouts and constraints.
* **Size:** the final width and height after layout. Shown for layouts, text, and images.
These values can differ from the **Transform** values when a [layout](/docs/editor/layouts/layouts-overview) or [constraint](/docs/editor/constraints/constraints-overview) positions the object.
## Target For
When a single object is selected, the **Target For** section lists everything that targets it, such as [constraints](/docs/editor/constraints/constraints-overview), [clipping](/docs/editor/manipulating-shapes/clipping), masks, draw order rules, and State Machine listeners.
Click the target button on a row to jump to the object that uses it:
* **Select on Stage** selects the object that targets this one.
* **Open in State Machine** opens the State Machine at the listener that uses this object.
The section only appears when something targets the selection.
## File properties
When nothing is selected, the Inspector shows file-level options.
These include:
* [Stage background colors](/docs/editor/interface-overview/stage#stage-background-colors) for Design and Animate modes
* Scripting optimization and debug settings
* [Shader targets](/docs/scripting/wgsl-shaders#shader-targets)
* [Tags](/docs/editor/tagging)
* [Default interpolation](/docs/editor/animate-mode/interpolation-easing#default-interpolation)
# Interface Overview
Source: https://rive.app/docs/editor/interface-overview/overview
Rive's interface only shows what is needed when you need it. It is divided into a few main panels, which are described below.
[YouTube video player](https://www.youtube.com/embed/-NumdcojOTs)
## File browser

The File Browser is where you create, open, organize, and manage your Rive files. You can also browse recent files, open Marketplace examples, switch between workspaces, and manage projects.
Read more on the [File Browser page](/docs/editor/interface-overview/file-browser).
## Toolbar

The Toolbar displays the tools you have available to create, rig, and manipulate items on the stage. In addition to these tools, the Toolbar houses a variety of options to allow you to customize the look of your file, set your main artboard, and export or share your file.
Read more on the [Toolbar page](/docs/editor/interface-overview/toolbar).
## Sidebar

The sidebar is the left side of the editor. It contains panels for navigating your file, managing assets, working with data, editing animations, and using the AI Agent.
Read more on the [Sidebar page](/docs/editor/interface-overview/sidebar).
## Inspector
The Inspector is the right sidebar in the editor. It shows the available properties and options for the current selection.

Read more on the [Inspector page](/docs/editor/interface-overview/inspector).
## Viewport

The Viewport is the central area between the Toolbar, Sidebar, and Inspector. It can display the Stage, scripts, and other panels.
The Stage is where you create and edit artboards, which contain the designs and animations in your Rive file.
Read more on the [Viewport page](/docs/editor/interface-overview/stage).
## Timeline

The Timeline surfaces from the bottom of the screen upon entering [animate mode](/docs/editor/fundamentals/design-vs-animate-mode). Here you can create new states, access playback controls, settings, and set keyframes for object parameters. Select a timeline from the left-hand list to switch between the respective timelines.
Read more on the [Timeline page](/docs/editor/fundamentals/design-vs-animate-mode).
## State Machine graph

When a state machine is selected, the Timeline is replaced by a graph. This is where you'll be working on the state machine.
Read more on the [State Machine page](/docs/editor/state-machine/state-machine).
## Debug Panel

The Debug Panel shows output and diagnostic information while you work. Use it to read console logs, find problems in your file, review AI Agent changes, run tests, and preview audio.
Read more on the [Debug Panel page](/docs/editor/interface-overview/debug-panel).
# Selection and Navigation
Source: https://rive.app/docs/editor/interface-overview/selection-and-navigation
Select objects, move through nested groups, and navigate the stage.
Use selection and navigation controls to choose objects, move through nested groups, and move around the stage.
> [!TIP]
>
> For a complete list of shortcuts, see [Keyboard Shortcuts](/docs/editor/keyboard-shortcuts).
## Selecting objects
[YouTube video player](https://www.youtube.com/embed/xQK498Y1J8M)
Click an object to select it. To select multiple objects, drag over them to create a marquee selection.
Hold `Shift` while clicking or dragging to add objects to the current selection or remove selected objects.
### Select objects inside groups
To select an object inside a group, double-click the object. This moves you one level down in the hierarchy, so you can select objects inside that group.

### Deep select
To select an object inside nested groups, hold `⌘` on macOS or `Ctrl` on Windows, then click the object.
Deep select lets you select an object directly, even when it is inside multiple groups.
> [!NOTE]
>
> [Targets](/docs/editor/fundamentals/groups#target-style) are directly selectable on the stage. You don't need to use **Deep Select** to select them.

### Select behind
When you hover over an object on the stage, Rive outlines the object that will be selected if you click.
If multiple objects overlap, press `Alt` to cycle through objects under the cursor. When the object you want is outlined, click to select it.
You can also right-click and choose **Select** to pick from a list of the objects under the cursor. Hover a name to highlight that object on the stage.

### Moving up and down the Hierarchy
Use `Enter` and `Esc` to move through nested objects in the hierarchy.
* Press `Enter` to move down into the selected group and select its first child.
* Press `Esc` to move up and select the parent of the current selection.

## Transform handles
When you select an object, handles appear on the stage so you can move, rotate, scale, and resize it. Which handles appear depends on the [transform tool](/docs/editor/interface-overview/toolbar#transform-tools) you're using.
### Gizmo
* **Red arrow:** drag to move the selection along its X axis only.
* **Green arrow:** drag to move the selection along its Y axis only.
* **Center dot:** drag to move the selection freely in any direction, like dragging the object itself.
* **Ring:** drag to rotate the selection around the gizmo's center. Hold `Shift` to snap to 45° steps.
* **Red square:** drag to scale the selection along its X axis. Hold `Shift` to scale proportionally.
* **Green square:** drag to scale the selection along its Y axis. Hold `Shift` to scale proportionally.
> [!NOTE]
>
> Artboards don't show a gizmo. Use the bounding box to move and resize them.
### Bounding box
With the **Select** tool, a bounding box surrounds the selection.
* **Corners:** drag to resize from that corner. The opposite corner stays put. Hold `Shift` to keep proportions, or `Alt` to resize around the origin.
* **Edges:** drag to resize from that side. The opposite side stays put. Hold `Alt` to resize around the origin.
* **Outside a corner:** drag just outside a corner to rotate the selection. Hold `Shift` to snap to 45° steps.
## Navigating the Stage
### Pan
To pan the stage, right-click and drag.
You can also hold `Spacebar` to temporarily switch to the Pan tool, then click and drag to move around the stage.
If you're using a trackpad, scroll left or right to pan horizontally.

### Zoom
To zoom in or out, place your cursor over the stage, then hold `⌘` on macOS or `Ctrl` on Windows and scroll.

You can also use keyboard shortcuts:
* Press `+` to zoom in.
* Press `-` to zoom out.
* Press `⌘` + `0` on macOS or `Ctrl` + `0` on Windows to return to 100%.
### Fit selection
Press `F` to fit the current selection in the viewable stage area.

If an object is selected, Rive fits that object in view. If an artboard is selected, Rive fits the artboard in view.
> [!TIP]
>
> If you lose track of an artboard or object on the stage, select it in the hierarchy and press `F` to fit it in view.
# Sidebar
Source: https://rive.app/docs/editor/interface-overview/sidebar
Use the sidebar to access editor panels and organize your workspace.
The sidebar is the left side of the editor. It contains panels for navigating your file, managing assets, working with data, editing animations, and using the AI Agent.

## Panels
The sidebar includes several panels:
* [Hierarchy](/docs/editor/interface-overview/hierarchy) - View and organize the objects in your file. It can also switch to [Spaces](/docs/editor/interface-overview/hierarchy#spaces), which group your artboards in the editor.
* [Data](/docs/editor/data-binding/overview) - Create and manage View Models, properties, and data binding.
* [Assets](/docs/editor/fundamentals/assets-overview) - Manage images, fonts, audio, and other assets used in your file.
* [Animations](/docs/editor/animate-mode/animate-mode-overview) - Create and manage animations and State Machines.
* [Agent](/docs/editor/ai-agent/ai-agent) - Use the AI Agent to help create, edit, and explore your file.
## Panel options
Use the **…** menu on a panel to access options such as filtering, sorting, collapsing the panel, or resetting the sidebar layout.
## Organizing panels
You can customize how panels appear in the sidebar.
* Toggle full sidebar height.
* Drag panels to change their order.
* Drag a panel into its own column.
### Open AI Agent in viewport
The Agent panel also has an option to open in the viewport, where it appears alongside the Stage or Script panel.
# Viewport
Source: https://rive.app/docs/editor/interface-overview/stage
Use the viewport to work with the Stage, scripts, and the AI Agent.
The viewport is the center area of the editor. It can show the [Stage](#stage), scripts, and the **AI Agent**.
You can [split the viewport](#splitting-the-viewport) to view multiple panels side by side or stacked vertically. This is useful when you want to edit artwork while viewing a script, or keep the AI Agent open alongside the Stage.

## Stage
The Stage is an infinite canvas where you can place artboards containing all your graphics.

[Artboards](/docs/editor/fundamentals/artboards) live on the stage. You can pan and zoom around the stage, select objects, and use guides or rulers to help position elements.
> [!TIP]
>
> To learn how to navigate and select items on the stage, see [Keyboard Shortcuts](/docs/editor/keyboard-shortcuts).
### View options menu

The View Options menu controls what appears on the stage while you work. Use it to adjust zoom, snapping, guides, and visual overlays for animation and interaction tools.
* **Zoom and snapping:** adjust the stage zoom level, enable snapping, or snap objects to pixels
* **User Cursors:** show or hide other users' cursors
* **Tool overlays:** show or hide gizmos, bones, targets, motion paths, joysticks, events, layouts, and text modifier ranges
* **Show Final Playback:** show the final playback state while editing
* **Rulers and guides:** show rulers, lock guides, or clear guides from the stage
#### Zoom and rotation
* **Rotation:** rotate your view of the stage. Your artwork isn't rotated. Click the lock icon in the field to stop trackpad twist gestures from rotating the view.
* **Zoom In** and **Zoom Out:** double or halve the zoom, around the center of the view.
* **Zoom to Fit:** zoom to fit the content in the view.
* **Zoom to 100%:** show the stage at actual size.
* **Reset Rotation:** turn the view back to no rotation.
#### Object types
The menu lists types of objects: **Bones**, **Targets**, **Stage Controls**, **Layouts**, and **Shapes & Images**. Each row has three buttons:
* **Select Only:** only this type of object can be selected on the stage.
* **Filter Trees:** show only this type of object in the [Hierarchy](/docs/editor/interface-overview/hierarchy) and timeline.
* **Visibility:** show or hide this type of object in this view.
#### Other options
* **Inactive Solos:** show the children of [solos](/docs/editor/manipulating-shapes/solos) that aren't active.
### Stage background colors
You can set separate stage background colors for Design mode and Animate mode.
Using different colors can make it easier to tell which mode you are in at a glance. This can help prevent accidentally editing keys or animation values when you meant to work in Design mode.
To change the stage background colors, deselect everything, then use the background color options in the [Inspector](/docs/editor/interface-overview/inspector). Each [space](/docs/editor/interface-overview/hierarchy#spaces) has its own background colors, and the Inspector edits the colors of the space you're viewing.
> [!NOTE]
>
> Stage background colors are only visible in the editor. They do not affect the artboard background, exports, or runtime appearance.
## Splitting the Viewport
To split the viewport, drag a panel into the viewport or click **Split Editor Right** from the panel options.
To open the **AI Agent** in the viewport, click the **…** button in the **Agent** panel in the sidebar, then select **Open in Viewport**.
### Viewport tabs
Each split shows its content as tabs.
* Click a tab to show it.
* Drag a tab to reorder it, move it to another split, or drop it on an edge to split the view.
* Right-click a tab to close the other tabs, the tabs to its left or right, or all tabs.
A tab shown in italics is a preview tab. Opening something else replaces it. Click or drag the tab to keep it open.
Use the **Tab Options** button to close tabs, or to open a stage or a script in that split.
### Maximizing a split
Click the **Maximize Viewport** button in a split's tab bar to expand that split to fill the editor below the toolbar. Click **Restore Viewport** to return to your layout.
You can also press `` ` `` to maximize the split under your cursor, and press it again to restore.
### Document view
Text documents whose [Text File Format](/docs/scripting/api-reference/file-format/text-file-format) script provides a preview show a **Document View** button in the tab bar. Click it to cycle between showing the text, the preview, or both side by side.
# Toolbar
Source: https://rive.app/docs/editor/interface-overview/toolbar
Access file, design, rigging, preview, and export tools from the Rive editor toolbar.

Use the toolbar to switch tools, create objects, adjust view options, invite collaborators, publish your file, and access file-level actions.
## Editor menu

The **Editor menu** contains file-level actions and editor settings.
Common actions include:
* [Revision History](/docs/editor/fundamentals/revision-history)
* [Export for Runtime](/docs/editor/exporting/exporting-for-runtime)
* [Export for Backup](/docs/editor/exporting/exporting-for-backup)
* [Share and Embed](/docs/editor/embed-urls/overview)
* [Render to Video or Image](/docs/editor/exporting/exporting-for-video-and-static-design)
### Sharing
* **Share File**: Invite people to this file. See [Invite](#invite).
* **Copy File URL**: Copy a link that opens this file in the editor.
### Editor settings
These options are under **Options** in the menu.
* **Use Horizontal Field Drag**: Drag number fields left and right to change their value, instead of up and down.
* **Pause Component Updates**: Stop [components](/docs/editor/fundamentals/components) on the stage from updating. Your changes to them show once you turn this off.
### Language
Use **Language** to change the language of the editor's interface. You can choose English, Español, or 简体中文. Languages marked **Beta** may have some text that isn't translated yet.
While you use a beta language, choose **Translation Feedback** to report problems or suggest fixes in the Rive Community.
You can also change the language from the account menu in the [File Browser](/docs/editor/interface-overview/file-browser#toolbar).
### File maintenance
These items at the bottom of the menu update older files:
* **Convert Inputs to ViewModels**: Replaces state machine inputs with view model properties. See [Migrating State Machine Inputs](/docs/editor/data-binding/migration-guide#state-machine-inputs).
* **Reset Layout Transforms**: Puts every [layout](/docs/editor/layouts/layouts-overview) back where its parent layout places it, removing stray X and Y offsets. This item only appears until the file has been reset.
## Tools

The **Tools** area lets you select, transform, draw, create objects, add rigging, and preview interactions.
Common tools include:
* [Select, translate, rotate, and scale tools](#transform-tools)
* [Stage tools](#stage-tools), such as events and joysticks
* [Artboards](/docs/editor/fundamentals/artboards) and [components](/docs/editor/fundamentals/components)
* [Shape and drawing tools](/docs/editor/fundamentals/shapes-and-paths-overview)
* [Bones tools](/docs/editor/manipulating-shapes/manipulating-shapes)
* Play the [State Machine](/docs/editor/state-machine/state-machine)
### Transform tools
Open the **Transform Tools** menu to pick how you move, rotate, and scale objects on the stage.
| Tool | Shortcut | What it does |
| - | - | - |
| **Select** | `V` | Select objects and move, rotate, or scale them. Shows the full [gizmo](/docs/editor/interface-overview/selection-and-navigation#gizmo) and the [bounding box](/docs/editor/interface-overview/selection-and-navigation#bounding-box). |
| **Translate** | `Q` | Move objects precisely. Shows only the move handles. |
| **Rotate** | `W` | Rotate objects. Shows only the rotation ring. |
| **Scale** | `E` | Resize objects proportionately or non-proportionately. Shows only the scale handles. |
Tap `Q`, `W`, or `E` to switch to that tool. Hold the key instead to use the tool temporarily. When you let go, the editor switches back to the tool you were using.
The menu also has a [Freeze](/docs/editor/fundamentals/origin#freeze) toggle (`Y`).
### Stage tools
The **Stage Control Tools** menu holds tools for objects that don't render. They control or organize other elements in your design or animation.
* [Event](/docs/editor/events/overview)
* [Joystick](/docs/editor/manipulating-shapes/joysticks)
* [Property Group](/docs/editor/data-binding/property-groups)
* [Effect Group](/docs/editor/manipulating-shapes/effect-groups)
## Invite

Use **Invite** to add collaborators to the file. You can also choose **Share File** in the [Editor menu](#editor-menu).
Only files in a shared project can be shared. To invite people to one of your personal files, move it to a shared project first.
## Publish

Use **Publish** to export, embed, or publish your file.
* [Export a .riv for runtime](/docs/editor/exporting/exporting-for-runtime)
* Publish to a [library](/docs/editor/libraries)
* [Embed](/docs/editor/embed-urls/overview)
* Publish to the [marketplace](/docs/community/marketplace-overview#marketplace-overview)
## Preview bound values
By default, data-bound values update while the state machine is playing.
Turn on the **Data Binding Preview Toggle** to preview bound values while editing.

## Mode toggle
Use the **Mode Toggle** to switch between **Design** and **Animate** mode. Press `Tab` to switch modes quickly.
* **Design Mode**: create, edit, import, and rig graphics.
* **Animate Mode**: create timelines, state machines, keys, and animation logic.
> [!WARNING]
>
> Editing objects while a timeline is selected in Animate Mode can create keys. Learn more about [Design and Animate Modes](/docs/editor/fundamentals/design-vs-animate-mode).

# Keyboard Shortcuts
Source: https://rive.app/docs/editor/keyboard-shortcuts
Navigate quickly with keyboard shortcuts
> [!NOTE]
>
> Press Shift + / in the editor to open the shortcuts panel.
## Tools
| Tools | Shortcut |
| - | - |
| Select Tool | V |
| Translate Tool | Q |
| Rotate Tool | W |
| Scale Tool | E |
| Rectangle Tool | R |
| Ellipse Tool | O |
| [Pen Tool](/docs/editor/fundamentals/pen-tool-overview) | P |
| [Bucket Tool](/docs/editor/design/freehand-drawing#bucket-tool) | Shift + U |
| [Text](/docs/editor/text/text-overview) | T |
| Help Tool | H (hold) |
| [Artboards](/docs/editor/fundamentals/artboards) | A |
| [Components](/docs/editor/fundamentals/components) | N |
| [Bones](/docs/editor/manipulating-shapes/bones) | B |
| Weight Tool | Shift + B |
| [Groups](/docs/editor/fundamentals/groups) | G |
| [Layouts](/docs/editor/layouts/layouts-overview) | L |
| Row | Shift + R |
| Column | Shift + C |
| Shape Builder | Shift + M |
| [Solos](/docs/editor/manipulating-shapes/solos) | S |
| [Joysticks](/docs/editor/manipulating-shapes/joysticks) | J |
| [Events](/docs/editor/events/overview) | Shift + E |
| [Freeze](/docs/editor/fundamentals/origin#freeze) | Y |
| Color Picker | I |
| Dependency Graph | D |
## Editor
| Purpose | Shortcut |
| - | - |
| Switch Animation Mode | Tab |
| Constrain Shape/Angle | Shift |
| Multi Select | hold Shift + click |
| Deep Select | macOS: ⌘ + click Windows: Ctrl + click |
| [Select Behind](/docs/editor/interface-overview/selection-and-navigation) | Alt |
| Nudge Object | Arrow Keys |
| Nudge Object (10x) | Shift + Arrow Keys |
| Edit Vertices | Enter w/ path selected |
| Group Selection | macOS: ⌘ + G Windows: Ctrl + G |
| Ungroup Selection | macOS: ⌘ + Shift + G Windows: Ctrl + Shift + G |
| Wrap in Layout | Shift + L |
| Add Child Layout | Shift + Alt + L |
| Duplicate | macOS: ⌘ + D Windows: Ctrl + D |
| Convert to Component | Shift + N |
| Remove Component | Shift + Alt + N |
| Swap Fill/Stroke | Shift + X |
| Set Opacity in 10% Steps | 1 to 0 with objects selected |
| Layer Forward | macOS: ⌘ + ] Windows: Ctrl + ] |
| Layer Backward | macOS: ⌘ + \[ Windows: Ctrl + \[ |
| Layer to Top | macOS: ⌘ + Opt + ] Windows: Ctrl + Alt + ] |
| Layer to Bottom | macOS: ⌘ + Opt + \[ Windows: Ctrl + Alt + \[ |
| Move Timeline Playhead | , or . |
| Move Timeline Playhead 10 frames | Shift + , or Shift + . |
| Move Playhead to Start/End | macOS: ⌘ + Shift + , or . Windows: Ctrl + Shift + , or . |
| Move Selected Keys | Alt + , or . Hold Shift to move 10 frames |
| Skip to Keys (Selected Row, Otherwise All) | macOS: ⌘ + , or . Windows: Ctrl + , or . |
| Key All Vertices | Shift + K |
| Resize Keyframe Selection | hold Alt + click and drag |
| Stagger Keyframes | macOS: hold ⌘ + Alt Windows: hold Ctrl + Alt |
| Previous/Next Animation | PageUp / PageDown |
| Disable State Machine Layer | macOS: ⌘ + M Windows: Ctrl + M |
| Select All | macOS: ⌘ + A Windows: Ctrl + A |
| Undo | macOS: ⌘ + Z Windows: Ctrl + Z |
| Redo | macOS: ⌘ + Shift + Z Windows: Ctrl + Shift + Z or Ctrl + Y |
| Copy / Paste / Cut | macOS: ⌘ + C / V / X Windows: Ctrl + C / V / X |
| Copy / Paste Style | macOS: ⌘ + Alt + C / V Windows: Ctrl + Alt + C / V |
| Duplicate on Drag | hold Alt |
| Create Shape From Center | hold Alt |
| Create Shape Symmetrically | hold Shift |
| Resize From Origin | hold Alt |
| Toggle Snapping | macOS: hold ⌘ + drag element Windows: hold Ctrl + drag element |
| Color Picker | macOS: Ctrl + C or I Windows: I |
| Search | macOS: ⌘ + K or ⌘ + F Windows: Ctrl + K or Ctrl + F |
| Reveal Keys for Selection | U |
| Filter Transform Properties | T |
| Filter Position Properties | P |
| Filter Scale Properties | S |
| Filter Rotation Property | R |
| Filter Opacity Property | O |
| Add to Property Filter | hold Shift |
The property filters share their keys with the Text, Pen, Solo, Rectangle, and Ellipse tools, and their Shift forms take Shift + R from Row and Shift + S from Align Bottom. They apply when objects are selected; otherwise the key reaches the tool or align action.
| Purpose | Shortcut |
| - | - |
| Play | Space |
| Play Default State Machine | Shift + Space |
| Delete Selection | Backspace |
| Toggle Display Mode | \` |
| Toggle Rulers & Guides | ; |
| Lock Guides | Alt + ; |
| Close Tab | macOS: ⌘ + W Windows: Ctrl + W |
| Reopen Closed Tab | macOS: ⌘ + Shift + T Windows: Ctrl + Shift + T |
| Shortcuts Panel | Shift + / |
| Quit Rive | macOS: ⌘ + Q |
| Preferences | macOS: ⌘ + , Windows: Ctrl + , (not while editing an animation) |
## Interpolation
Applies to the selected keys.
| Purpose | Shortcut |
| - | - |
| Hold | F6 |
| Linear | F7 |
| Ease In Out (Cubic) | F8 |
| Ease In (Cubic) | Shift + F8 |
| Ease Out (Cubic) | macOS: ⌘ + Shift + F8 Windows: Ctrl + Shift + F8 |
| Ease In Out (Cubic Value) | F9 |
| Ease In (Cubic Value) | Shift + F9 |
| Ease Out (Cubic Value) | macOS: ⌘ + Shift + F9 Windows: Ctrl + Shift + F9 |
| Elastic | F10 |
## Panels
| Purpose | Shortcut |
| - | - |
| Hierarchy | macOS: ⌘ + 1 Windows: Ctrl + 1 |
| Data | macOS: ⌘ + 2 Windows: Ctrl + 2 |
| Assets | macOS: ⌘ + 3 Windows: Ctrl + 3 |
| Animations | macOS: ⌘ + 4 Windows: Ctrl + 4 |
| Agent | macOS: ⌘ + 5 Windows: Ctrl + 5 |
| Show Bound Values | macOS: ⌘ + B Windows: Ctrl + B |
| Next/Previous File Tab | Ctrl + Tab / Ctrl + Shift + Tab |
## Align and origin
| Purpose | Shortcut |
| - | - |
| Align Top / Bottom | Shift + W / Shift + S |
| Align Left / Right | Shift + A / Shift + D |
| Align Center / Middle | Shift + H / Shift + V |
| Origin Top / Bottom | Alt + W / Alt + S |
| Origin Left / Right | Alt + A / Alt + D |
| Origin Center / Middle | Alt + H / Alt + V |
## View
| Purpose | Shortcut |
| - | - |
| Fit selection to screen | F |
| Zoom (mouse) | macOS: ⌘ + Mouse Wheel Windows: Ctrl + Mouse Wheel |
| Zoom (keyboard) | + and - |
| Zoom to 100% | macOS: ⌘ + 0 Windows: Ctrl + 0 |
| Zoom (marquee) | Z (hold) |
| Pan | Right-click + drag Space + drag |
| Toggle Graph Editor | Shift + F3 |
| Cycle Graph Type | Shift + G |
| Auto-Zoom Height | Shift + F |
## Hierarchy
| Purpose | Shortcut |
| - | - |
| Select parent | Esc |
| Select 1st child | Enter |
| Scroll hierarchy and timeline to selection | X |
| Rename | macOS: ⌘ + R Windows: Ctrl + R |
| Expand/Collapse all children | macOS: Opt + click expand icon Windows: Alt + click expand icon |
| Show/hide self only | macOS: ⌘ + click eye icon Windows: Ctrl + click eye icon |
| Show/hide parents only | macOS: Opt + click eye icon Windows: Alt + click eye icon |
# Arranging Children
Source: https://rive.app/docs/editor/layouts/arranging-children
Control how a Layout arranges its children with direction, alignment, padding, and gap.
A Layout arranges the children that participate in it. This page covers the settings you set on the parent: which direction its children flow, how they wrap and align, how much space surrounds and separates them, and how the Layout itself looks.
Apart from clip and styles, these settings only affect children that participate in the Layout: other Layouts, shapes, text, and images set to **Layout** in the **Inspector**, and component instances in **Layout** mode. Absolute children ignore them. To control a child's own size or pin it to the parent's edges, see [Sizing and Positioning](/docs/editor/layouts/sizing-and-positioning).
## Layout type
The layout type decides the overall pattern a Layout uses to arrange its children:
* **Row:** Places children side by side, from left to right.
* **Column:** Places children one below another, from top to bottom.
* **Grid:** Places children in cells defined by columns and rows. See [Grid](/docs/editor/layouts/grid-and-stack#grid).
* **Stack:** Places all children in the same space, layered on top of each other. See [Stack](/docs/editor/layouts/grid-and-stack#stack).
Children are arranged in hierarchy order. To change the order, reorder the children in the **Hierarchy** or drag them on the stage.
To flip the order of a Row or Column without reordering the hierarchy, select the **Reverse** checkbox. A reversed Row runs from right to left, and a reversed Column runs from bottom to top.
The direction a Layout arranges its children in is its **main axis**. A Row's main axis is horizontal, and a Column's is vertical. The other direction is the **cross axis**. Several settings, including alignment, wrap, and [Fill](/docs/editor/layouts/sizing-and-positioning#fill), behave differently along each axis.
## Alignment
Alignment decides where children sit within the Layout when they don't take up all of its space. Select one of the nine points on the alignment widget in the **Inspector**, such as top-left or center.

Alignment moves children as a group. In a Row aligned to the center, the children stay next to each other and the group sits in the middle of the Row.
### Space between
To spread children out along the main axis instead, click the selected point again. The first child moves to the start of the Layout, the last child moves to the end, and the remaining space is shared evenly between them. The cross-axis alignment stays the same. Click the point again to group the children back together.

Tip
**Example - A navigation bar**
A navigation bar is a Row containing a logo, a set of links, and a profile button. With space between, the logo sits at the left edge, the profile button at the right edge, and the links in the middle. When the bar gets wider, the space between them grows while each item stays the same size.
## Wrap
Wrap decides what happens when a Row or Column runs out of room for its children:
* **No Wrap:** Children stay on a single line and extend past the Layout's edge.
* **Wrap:** Children that don't fit move onto a new line below a Row, or a new column beside a Column.
* **Wrap Reverse:** Same as **Wrap**, but new lines are added in the opposite direction, above a Row or before a Column.

Use Wrap for content that should reflow onto more lines as the space gets narrower, such as a set of tags or a gallery of thumbnails. This tutorial builds a file whose elements reflow as it's resized:
[YouTube video player](https://www.youtube.com/embed/_dE4ndRZB6U)
## Padding, gap, and margin
Rive has three settings that add space in a Layout. Padding and gap are set on the parent, and margin is set on the child.
* **Padding:** Space between the parent's edges and its children. Padding is set on the parent and pushes all of its children inward.
* **Gap:** Space between neighboring children. Gap is set on the parent and applies evenly between every pair of children.
* **Margin:** Space around one child. Margin is set on the child and only affects that child. See [Margin](/docs/editor/layouts/sizing-and-positioning#margin).
Tip
**Example - Spacing out a list**
A Column contains three list items. To keep the items 24 points from the Column's edges, add 24 points of padding to the Column. To put 12 points between each item, set the Column's vertical gap to 12. To give one item extra space above it, such as the start of a new section, add a top margin to that item only.
> [!TIP]
>
> Prefer gap over margins for even spacing. If every child has a 10-point margin, neighboring children end up 20 points apart, because their margins add together. A 10-point gap puts exactly 10 points between each child and nothing at the edges.
Padding only affects children that participate in the Layout. To add space around a label inside a button, the label needs to participate in the button's Layout. You can either set the label to **Layout** in the **Inspector**, or wrap it in its own Layout.
### Setting padding
Padding can be set the same on both sides of an axis, or separately on each edge. Use the edge toggle to show a field for each edge, and use the unit toggle to switch between points and percentages.
Padding and Margin
### Setting gap
Gap can be set separately for the horizontal and vertical directions, in points or as a percentage of the Layout's width or height. In a Row that wraps, the horizontal gap separates children on the same line, and the vertical gap separates the lines.

## Text direction
Text direction decides whether a Layout reads left to right or right to left. Use it to support right-to-left languages such as Arabic and Hebrew.
* **Inherit:** Use the parent Layout's direction. This is the default.
* **Left to Right:** Rows run from left to right, and text aligns to the left.
* **Right to Left:** Rows run from right to left, and text aligns to the right.
The direction passes down to every child Layout set to **Inherit**, so you can usually set it once on the artboard or an outer Layout.
[YouTube video player](https://www.youtube.com/embed/oLjFOu-UFxM)
## Clip
Select the clip toggle to hide anything inside the Layout that extends past its edges. Clip applies to all of the Layout's content, including absolute children and content that doesn't participate in the Layout.

## Styles
Layouts can have fills, strokes, feathers, blend modes, and corner radii, just like other objects in Rive. This means a Layout can be the visible shape of a button or card, rather than needing a separate rectangle behind its content.
Styles can be drawn in the **Background**, behind the Layout's children, or in the **Foreground**, in front of them. For example, you might place a fill and a feathered shadow behind the children while drawing a stroke in front.
Corner radius applies to the Layout's styles and to its clipping edges, so clipped content follows the rounded corners.
# Component Sizing
Source: https://rive.app/docs/editor/layouts/component-sizing
Control how component instances scale, fit, and reflow within their parent.
A [component](/docs/editor/fundamentals/components) instance is a whole artboard placed inside another artboard. When that instance sits inside a Layout, its sizing mode decides how it responds to the space it's given. Choose a mode based on how you want the component and its contents to respond as that space changes.
* **Node** - Scale the component as a single object. It doesn't take part in the Layout.
* **Leaf** - Fit the component's contents within the Layout, the way an image fits its frame. The contents scale but don't reflow.
* **Layout** - Take part in the Layout like any other child, and resize the component's artboard so the Layouts inside it can reflow.
Use **Layout** mode to build responsive designs out of reusable pieces, such as a button component that's used in several menus and hugs a different label in each one.

## Node
**Node** is the default sizing mode. The component behaves like a regular object or group, with its contents scaling together based on the **Scale** property.
Use Node when the component doesn't need to respond to the size of a parent Layout.
Node is also the only mode that supports a [Mesh or N-Slice](/docs/editor/fundamentals/components#deform).
## Leaf
**Leaf** fits a component's contents within the space provided by its parent Layout or artboard. The component's contents scale rather than reflow.
Leaf is useful for responsive components that don't contain Layouts themselves, such as an illustration or icon that needs to fit within the available space.

### Fit
**Fit** determines how the component's contents scale within the available space.
* **Fill (Default)** - Fill the available space. If the aspect ratios differ, the content stretches to fit.
* **Contain** - Fit all content within the available space while preserving its aspect ratio. This may leave unused space.
* **Cover** - Fill the available space while preserving the content's aspect ratio. Some content may extend beyond the available space.
* **Fit Width** - Scale the content to the width of the available space. This may result in clipping or unused space vertically.
* **Fit Height** - Scale the content to the height of the available space. This may result in clipping or unused space horizontally.
* **None** - Keep the content at the original size of its artboard. This may result in clipping or unused space.
* **Scale Down** - Scale the content down to fit while preserving its aspect ratio, but don't scale it up when the available space is larger.
### Alignment
**Alignment** determines where the component's contents are positioned when they don't fill the available space. Choose from nine positions using the alignment grid, including center, corners, and edges.
For more precise positioning, use **Alignment Position X/Y**. Values range from `-1` to `1` on each axis:
* **X:** `-1` is left, `0` is center, and `1` is right.
* **Y:** `-1` is top, `0` is center, and `1` is bottom.
You can also use values between these positions. For example, an X value of `0.5` positions the content halfway between center and right.
### Fits to layout parent
**Fits to layout parent** appears when a Leaf instance's direct parent isn't a Layout, such as when it's inside a **Solo** or a bone, with a Layout higher up.
* **On**: Size against the nearest Layout, reaching through the **Solo** or bone. Setting an instance's **Mode** to **Leaf** turns this on.
* **Off**: Size only against a Layout that is the direct parent.
## Layout
**Layout** resizes the component's artboard instead of scaling its contents. As the artboard changes size, Layouts within the component can reflow their contents to respond to the available space.
Use Layout for responsive components whose internal content needs to resize or reflow, such as buttons that hug their text or components that fill the width of a parent Layout.

### Size
In Layout mode, the component's width and height can each use one of three sizing behaviors. These work the same way as they do for Layouts. See [Width and height](/docs/editor/layouts/sizing-and-positioning#width-and-height).
* **Fixed** - Use a defined width or height. Fixed dimensions can use either units or percentage values.
* **Hug** - Resize to fit the component's contents. This is useful when content such as text needs to determine the component's size.
* **Fill** - Expand to fill the available space within the parent Layout or artboard.
When using **Fixed**, enter a value for the component's width or height and use the unit control to switch between units and percentages.
Unlike the **Scale** property, changing the size of a component in Layout mode changes the dimensions of its artboard and allows its contents to reflow. In most cases, avoid using **Scale** with components in Layout mode.
# Grid and Stack
Source: https://rive.app/docs/editor/layouts/grid-and-stack
Arrange children in columns and rows, or layer them on top of each other.
Rows and Columns arrange children in a single line. Grid and Stack cover two other common patterns: a Grid places children in cells across columns and rows, and a Stack layers children on top of each other in the same space.
To use either one, select a Layout and set its layout type to **Grid** or **Stack** in the **Inspector**. See [Layout type](/docs/editor/layouts/arranging-children#layout-type).
[YouTube video player](https://www.youtube.com/embed/54fj9_zUemc)
## Grid
A Grid Layout arranges its children in cells made of columns and rows. Use a Grid when content should line up in two directions, such as an inventory screen, a photo gallery, or a dashboard of cards.
A new Grid starts with one column and one row. Add columns and rows in the **Inspector** to build out the grid. While the Grid is selected, the stage shows guides for each cell and shading for the gaps between them.
### Sizing columns and rows
Each column and row (or *track*) has its own size. Tracks use the same scale types as Layouts, applied to the whole column or row:
* **Fill:** The track takes a share of the leftover space, measured in `fr` (fill ratio) units. Three columns set to `1fr` split the width equally, while a `2fr` column takes twice the space of a `1fr` column. New tracks use `1fr`.
* **Fixed:** The track has a set width or height, in points or as a percentage of the Grid.
* **Hug:** The track shrinks or grows to fit the largest child inside it.
Drag tracks to reorder them. To edit several tracks at once, hold Shift and click their track numbers.
To add space between columns and rows, use the Grid's [gap](/docs/editor/layouts/arranging-children#setting-gap). The horizontal gap separates columns, and the vertical gap separates rows.
Tip
**Example - A sidebar and content grid**
A two-column Grid has a Fixed `240` point column for a sidebar and a `1fr` column for the main content. When the Grid gets wider, the sidebar stays 240 points wide and the content column takes all of the extra space.
### Placing children in cells
Children are placed into the Grid in hierarchy order. Each row is filled from left to right before moving to the next row.
To control where a child goes, select the child and use the **Grid Cell** options in the **Inspector**:
* **Cell:** The column and row to place the child in. By default, children are placed automatically in the next available cell.
* **Span:** The number of columns or rows the child covers.
When a child spans more than one cell, the children after it move on to the next available cells. If there are more children than cells, Rive adds rows to fit them. To control the size of those extra rows, add them to the Grid yourself and set their scale type.
To make a child fill its whole cell, set its width and height to **Fill**.
> [!TIP]
>
> A component instance in **Layout** mode set to **Fill** fills its cell, but can't use Grid Cell options such as **Span**. To span a component across cells, wrap the instance in a Layout, set that Layout's width and height to **Fill**, and set the span on the Layout.
### Animating a Grid
You can key track sizes, gaps, and Grid Cell spans and positions, which lets you animate children moving to new cells. The number of columns and rows can't be animated.
## Stack
A Stack Layout places all of its children in the same space, layered on top of each other. Use a Stack for anything made of layered parts, such as a card with a background, artwork, and a label, or a button with an icon over a shape.
Children are drawn in hierarchy order. The topmost child in the **Hierarchy** is drawn in front, and the bottommost child is drawn at the back.
### Sizing and positioning layers
Each child's size decides how much of the Stack it covers:
* **Fill:** The child covers the whole Stack. Use Fill for backgrounds and for layers that use their own padding and alignment to place their content.
* **Fixed** or **Hug:** The child keeps its own size, and the Stack's [alignment](/docs/editor/layouts/arranging-children#alignment) decides where it sits.
Layers follow the same sizing rules as children in a Row or Column. See [Sizing and positioning](/docs/editor/layouts/sizing-and-positioning).
Content larger than the Stack overflows based on its alignment. A centered Stack overflows equally on all sides, while a Stack aligned to the bottom-left overflows up and to the right.
Tip
**Example - Inventory item card**
An item card is a Stack with four layers: a badge, the item info, the item art, and a background. Each layer is a Layout set to Fill, so they all cover the card. Each layer uses its own padding and alignment to place its content: the badge sits in the top-left corner, and the item name and category are aligned to the bottom. An inventory screen then places these cards in a Grid, with one card spanning two columns.
# Layout Animation
Source: https://rive.app/docs/editor/layouts/layout-animation
Animate Layouts smoothly to their new position and size when content reflows.
When a Layout resizes or its content changes, the Layouts inside it move to new positions and sizes. By default, they jump there instantly. Layout animation makes them move there smoothly instead, over a duration and with easing that you choose.

> [card] [Learn by remixing](https://rive.app/community/files/28493-enable-layout-animation?utm_source=docs\&utm_medium=docs_link_card\&utm_campaign=docs_to_marketplace_links)
>
> Open this file on Marketplace, then click Remix to experiment in the Rive Editor.
## How Layout animation works
Layout animation is set on each Layout, and it controls how **that Layout** moves and resizes. It doesn't control the Layout's children. Each Layout uses one of three modes:
* **None:** The Layout jumps to its new position and size. This is the default.
* **Inherit:** The Layout animates using the duration and easing of its parent Layout.
* **Custom:** The Layout animates using its own duration and easing.
To animate a group of children, such as the items in a list, set the parent to **Custom** and each child to **Inherit**. You can then change the duration and easing for all of them in one place on the parent.
Tip
**Example - Reordering a list**
A Column contains five list items. The Column's Layout animation is set to **Custom** with a 0.3-second duration and cubic easing, and each list item is set to **Inherit**. When an item is removed, the items below it slide up to fill the gap instead of jumping.
## Adding Layout animation
**Step 1**
Select a Layout and click **+** in the **Enable Layout Animation** section of the **Inspector**.
**Step 2**
Select **None**, **Inherit**, or **Custom**.
**Step 3**
If you selected **Custom**, set the **Duration** and the [interpolation](/docs/editor/animate-mode/interpolation-easing) the Layout uses to move to its new position and size.
The easing graph shows how the move progresses over the duration, with time running left to right and progress running bottom to top. For **Cubic**, drag the handles on the graph to shape the curve.
# Creating Layouts
Source: https://rive.app/docs/editor/layouts/layout-tools
Draw new Layouts, wrap existing content in Layouts, and move Layouts into other Layouts.
You can start a responsive design from empty Layouts, or add Layouts to artwork you've already made. This page covers each way to create a Layout and how to move Layouts in and out of each other.
## Drawing a Layout
The Layout tools are in the **Arrangement Tools** menu in the toolbar.

To draw a single, empty Layout, select the **Layout** tool (L ) and drag on the stage.
* Drag on the artboard to create an [absolute](/docs/editor/layouts/sizing-and-positioning#relative-and-absolute-positioning) Layout that's positioned freely.
* Drag on top of an existing Layout to create a relative child of that Layout.
Any objects inside the area you drag are wrapped in their own Layouts and placed inside the new Layout as absolute children.
### Drawing a Row, Column, Grid, or Stack
The **Row**, **Column**, **Grid**, and **Stack** tools draw a Layout of that [type](/docs/editor/layouts/arranging-children#layout-type) that already contains children, so you can start arranging content right away.
* **Row** (Shift +R ) and **Column** (Shift +C ): While dragging, press ↑ or ↓ , or a number key, to set the number of children. The children's widths and heights are set to **Fill**.
* **Grid:** Draws a Grid with two `1fr` columns and two `1fr` rows. While dragging, press ↑ or ↓ to add or remove a column and row together, or a number key to set the number of each.
* **Stack:** Draws a Stack containing layered children of decreasing size.
## Wrapping content in a Layout
To add a Layout around content you've already made, select one or more objects and do one of the following:
* Right-click the selection on the stage or in the **Hierarchy**, then select **Wrap in** > **Layout**.
* Press Shift +L .
* Click the **Wrap in Layout** button at the top of the **Inspector**.
If every selected object is a group, the button becomes **Convert to Layout**. It turns the groups into Layouts and keeps their children, instead of adding a new Layout around them.
> [!TIP]
>
> Shapes, text, and images don't always need a wrapper Layout. To make one participate in its parent Layout directly, select it and choose **Layout** instead of **Node** at the top of the **Inspector**. See [What takes part in a Layout](/docs/editor/layouts/layouts-overview#what-takes-part-in-a-layout).
## Adding a child Layout
To add an empty Layout inside the selected Layout, click **Add Child Layout** in the **Inspector**. The new child's width and height are set to **Fill**.

## Moving Layouts into other Layouts
You can move any Layout into another Layout at any time:
* **In the Hierarchy:** Drag the Layout onto its new parent.
* **On the stage:** Drag the Layout over its new parent. An indicator shows where among the parent's children it will be inserted.

When you drag any object over a Layout on the stage, it becomes a child of that Layout when you drop it. To move an object over a Layout without putting it inside, hold Cmd (macOS) or Ctrl (Windows) while dragging.
To remove a Layout, select it on the stage or in the **Hierarchy** and press Delete .
# Responsive Design
Source: https://rive.app/docs/editor/layouts/layouts-overview
Build graphics that adapt when the space around them changes size.
A responsive graphic adapts when the space it lives in changes size. A button grows to fit a longer label, a menu reflows from one column to two on a wider screen, and a card stays pinned to the corner of a resizing window.
In Rive, that space is the artboard. In the editor, you change it by resizing the artboard. In your app or game, the artboard takes the size of the view or canvas it's drawn into. Layouts let you define how your content responds when that size changes.
[YouTube video player](https://www.youtube.com/embed/jANBKRidBtk)
## Freeform and Layout content
By default, Rive content is freeform. Each object has a position, rotation, and scale, and stays exactly where you put it. When the artboard changes size, freeform content doesn't move.
A **Layout** is a container that positions and sizes its content using rules instead of fixed coordinates. Rive's Layouts work much like Flexbox and CSS Grid on the web: a Layout can arrange its children in a row, a column, a grid, or a stack, with padding, gaps, and alignment.
You don't have to choose between freeform and Layout content. You decide which objects follow Layout rules, and you can mix both in the same artboard, or even inside the same Layout.
## How Layouts work
Responsive design in Rive comes down to a few ideas. Once these click, the rest of the Layout settings are details.
### The artboard is the root Layout
The artboard itself is a Layout. It has its own Layout settings in the **Inspector**, and the Layouts you add inside it respond to its size. When the artboard resizes, that change flows down through every Layout inside it.
### Layouts nest inside other Layouts
Most responsive designs are built from Layouts inside other Layouts. The outer Layout is the **parent**, and the Layouts inside it are its **children**. Each level handles one part of the design, such as a page made of rows, rows made of cards, and cards made of an image and a label.

In the example above, the outer Layout (green) arranges its children in a column. One of those children (red) is a row of four battery indicators (blue), each set to take an equal share of the row's width. Each indicator is itself a column containing a battery graphic and a label (pink). When the outer Layout resizes, every level adjusts.
> [card] [Learn by remixing](https://rive.app/community/files/26209-layouts-example/?utm_source=docs\&utm_medium=docs_link_card\&utm_campaign=docs_to_marketplace_links)
>
> Open this file on Marketplace, then click Remix to experiment in the Rive Editor.
### Parents arrange, children size themselves
Layout settings split into two groups, and knowing which group a setting belongs to makes Layouts much easier to work with:
* **The parent arranges its children.** Direction (row, column, grid, or stack), wrapping, alignment, padding, and gap are set on the parent and control where its children go.
* **Each child sets its own size.** Width, height, and margin are set on the child.
Each child's width and height uses one of three scale types:
* **Fixed:** A set size, in points or as a percentage of the parent.
* **Hug:** Shrinks to fit the child's own content, such as a label that's as wide as its text.
* **Fill:** Expands to take up the available space in the parent. When several children use Fill, they share the space.
If a setting doesn't seem to do anything, check whether you've set it on the right object. For example, to add space around a button's label, add padding to the button, not to the label.
Tip
**Example - A button that fits its label**
A button is a Layout set to **Row** with **Hug** width and height, and with padding on each side. Inside it is a text object set to participate in the Layout. Because the button hugs its content, changing the label from "OK" to "Continue" makes the button wider, while the padding stays the same.
### Absolute and relative positioning
A Layout child is positioned in one of two ways:
* **Relative:** The parent decides where the child goes, based on its direction, alignment, and gap. Relative children reflow when the parent changes size or when other children are added or removed.
* **Absolute:** The child ignores the parent's arrangement and pins itself to the parent's edges instead, such as 16 points from the top and right. Absolute children don't affect the position of their siblings.
Use the toggle at the top-right of the Layout section in the **Inspector** to switch between absolute and relative.

## What takes part in a Layout
A Layout arranges only the children that participate in it. Other content inside a Layout moves with the Layout but isn't arranged in its rows, columns, or grid.
| Content | How it behaves inside a Layout |
| - | - |
| Layouts | Always participate. |
| Shapes, text, and images | Participate when you select **Layout** instead of **Node** at the top of the **Inspector**. A shape, text, or image switched to Layout starts with **Hug** width and height. |
| Component instances | Participate when their mode is **Layout**. In **Leaf** mode, they're scaled to fit the parent Layout. See [Component Sizing](/docs/editor/layouts/component-sizing). |
| Groups | Don't participate themselves, but the content inside them can. |
| Everything else, such as paths, bones, and joysticks | Moves with the Layout, but isn't arranged by it. |
Text, images, and parametric shapes (rectangles, ellipses, triangles, polygons, and stars) that sit directly inside a Layout without participating are resized to fill that Layout. This is why many designs wrap each piece of content in its own Layout: the outer Layout arranges the wrappers, and each wrapper sizes its content.
For artwork that needs to resize without distorting, such as a custom-drawn button background, see [N-Slicing](/docs/editor/layouts/n-slicing).
## Breaking out of a Layout
Objects inside a Layout can still use Rive's freeform tools. You can move, scale, and rotate an object away from where the Layout put it, and you can apply [constraints](/docs/editor/constraints/constraints-overview) to it. This is useful for animation. For example, a list item can sit in its Layout position until it's selected, then animate out to the center of the screen.
[YouTube video player](https://www.youtube.com/embed/mAd2z5b4eNY)
## Previewing responsive behavior
To see how your design responds, resize the artboard on the stage and watch your Layouts adjust. Try very narrow and very wide sizes to find where the design breaks.
> [!TIP]
>
> If Layouts aren't visible on the stage, open the **View Options** menu and make sure **Layouts** is enabled.
>
> 
## Responsive graphics at runtime
At runtime, the artboard is drawn into a container that's sized by your app or game. To make the artboard take the size of that container, set the runtime's fit mode to **Layout**.
> [!WARNING]
>
> The default fit mode, **Contain**, scales the whole artboard as a single image. Your Layouts won't respond to the container until you change the fit mode to **Layout**.
See [Artboard size at runtime](/docs/editor/fundamentals/artboards#artboard-size-at-runtime) for how each fit mode behaves, and [Runtime layout](/docs/runtimes/layout) for how to set it on each platform.
## Learning more
* [Creating Layouts](/docs/editor/layouts/layout-tools): Create Layouts and wrap existing content in them.
* [Sizing and Positioning](/docs/editor/layouts/sizing-and-positioning): Set a child's width and height, margin, and absolute position.
* [Arranging Children](/docs/editor/layouts/arranging-children): Set a parent's direction, alignment, padding, and gap.
* [Grid and Stack](/docs/editor/layouts/grid-and-stack): Arrange children in cells or layer them on top of each other.
* [Component Sizing](/docs/editor/layouts/component-sizing): Control how component instances respond to their parent Layout.
* [Scrolling](/docs/editor/layouts/scrolling): Let content scroll when it doesn't fit.
* [Layout Animation](/docs/editor/layouts/layout-animation): Animate children as they move to new positions.
* [N-Slicing](/docs/editor/layouts/n-slicing): Resize artwork without distorting its corners and edges.
> [!NOTE]
>
> See the [Layouts playlist](https://www.youtube.com/playlist?list=PLujDTZWVDSsGvor80PkjHaZ3hNNo6s_ef) on Rive's YouTube channel for more Layout tutorials.
# N-Slicing
Source: https://rive.app/docs/editor/layouts/n-slicing
Resize images and artwork without stretching their corners and edges.
When artwork is resized, everything in it stretches, including details that should stay the same size, such as rounded corners or a decorative border. N-Slicing divides artwork into segments and decides which ones stay fixed and which ones scale, so it can resize without distorting.
N-Slicing is based on 9-slicing, a technique common in game design. A 9-slice divides an image into nine segments. The four corners keep their size, and the edges and center stretch or tile to fill the space. Rive's N-Slicing works the same way, but you can create any number of segments, on both images and vector artwork.
## N-Slicing in responsive designs
N-Slicing is useful for artwork that needs to fit a Layout, such as a button background, a speech bubble, or a panel frame. Place an N-Slice directly inside a Layout, and it resizes to fill that Layout while its fixed segments keep their size. See [What takes part in a Layout](/docs/editor/layouts/layouts-overview#what-takes-part-in-a-layout).
## Creating an N-Slice
You can apply an N-Slice to an image, to a group of vector objects, or to a component instance.
### On an image
**Step 1**
Select the image.
**Step 2**
In the **Deform** section of the **Inspector**, click **+** and select **N-Slice**. You can also right-click the image on the stage or in the **Hierarchy** and select **Deform** > **N-Slice**.
**Step 3**
Position the axes and set the tile modes. See [Setting up an N-Slice](#setting-up-an-n-slice).
**Step 4**
Click **Done** in the **Inspector** or on the stage.
### On vector artwork
**Step 1**
Select the artwork. If it's already in a group, select the group and click **Convert to N-Slice** in the **Inspector**. Otherwise, select the objects and click **N-Slice selection** in the **Inspector**, or right-click them and select **Wrap in** > **N-Slice**.
**Step 2**
With the N-Slice group selected, click **Edit N-Slice** in the **Inspector** or press Enter .
**Step 3**
Position the axes. See [Setting up an N-Slice](#setting-up-an-n-slice).
**Step 4**
Click **Done** in the **Inspector** or on the stage.
### On a component instance
A [component](/docs/editor/fundamentals/components#deform) instance with **Mode** set to **Node** can take an N-Slice the same way an image can. The component draws its artboard as a flat image and slices that image, so, like an image, it can look soft when scaled up.
**Step 1**
Select the component instance and set **Mode** to **Node**.
**Step 2**
In the **Deform** section of the **Inspector**, click **+** and select **N-Slice**.
**Step 3**
Position the axes and set the tile modes the same way you would for an image.
## Setting up an N-Slice
To change an N-Slice, select it and click **Edit N-Slice** in the **Inspector**, right-click it and select **Edit N-Slice**, or press Enter . When you're finished, click **Done Editing** to leave edit mode and select the sliced object again.
> [!NOTE]
>
> Set up your N-Slice before resizing the image or group. You can adjust axes on artwork that's already been resized, but it's harder to position new ones accurately.
### Fixed and scaling segments
Segments alternate between fixed and scaling, starting with a fixed segment. In a 9-slice, that means fixed, then scaling, then fixed, along both the horizontal and vertical axes.
In edit mode, fixed segments have solid blue borders, and scaling segments have dashed borders.
On vector artwork, set the N-Slice group's **Size** in the **Inspector** to choose the size it draws its contents at. Fixed segments keep their size, and scaling segments absorb the difference.
Because segments alternate by position, deleting an axis swaps the segments after it: fixed segments become scaling, and scaling segments become fixed. To delete an axis, click the delete button next to it in the **Inspector**.
### Positioning axes
A new N-Slice has four axes, two vertical and two horizontal, which divide the artwork into nine segments. Drag an axis to move it, or enter its position in the **Inspector** in points or as a percentage.
To add an axis, drag inward from one of the white handles on the edges of the artwork. A new axis is created with a mirrored partner on the opposite side, which keeps the fixed and scaling segments alternating. To create a single axis instead, hold Cmd (macOS) or Ctrl (Windows) before you start dragging.
### Setting tile modes
Tile modes control how a scaling segment fills its space. They're only available on images and component instances.
* **Stretch:** The segment stretches to fill the space.
* **Repeat:** The segment tiles to fill the space.
* **Hidden:** The segment isn't drawn.
**Hidden** also works on fixed segments. **Stretch** and **Repeat** have no effect on them, because fixed segments don't change size.
**Step 1**
Open the N-Slice's edit mode.
**Step 2**
Click a segment on the stage. Its tile is highlighted in the **Inspector**.
**Step 3**
Select a tile mode from the dropdown in the **Inspector**.
# Scrolling
Source: https://rive.app/docs/editor/layouts/scrolling
Let Layout content scroll when there is more of it than fits in the available space.
As a responsive design gets smaller, its content eventually stops fitting. A Layout has three ways to handle content that's larger than the space available:
* **Reflow:** Use [Wrap](/docs/editor/layouts/arranging-children#wrap) to move content onto more rows or columns.
* **Shrink:** Use [Fill](/docs/editor/layouts/sizing-and-positioning#fill) and [size constraints](/docs/editor/layouts/sizing-and-positioning#size-constraints) so content gets smaller, down to a minimum size.
* **Scroll:** Keep the content at its full size and let people scroll to see the rest.
Scrolling is the right choice when the amount of content can grow without a limit, such as a list of messages, a feed, or a menu with many options.
## How scrolling works in Rive
Scrolling in Rive is a [constraint](/docs/editor/constraints/constraints-overview) that you add to a Layout. A scroll region is made of three levels of Layouts:
* **Scroll view:** The Layout that defines the visible area. Its size usually comes from the rest of your responsive design, such as a Fill height in a Column.
* **Scroll content:** A Layout inside the scroll view that holds everything that scrolls. This Layout gets the **Scroll** constraint. Set it to **Hug** so it grows with its content. If the scroll content holds text directly, such as a long block of text, also select [Hug past bounds](/docs/editor/layouts/sizing-and-positioning#hug) so it can grow larger than the scroll view. Scroll content made of child Layouts doesn't need this.
* **Scroll items:** The Layouts inside the scroll content, such as the rows of a list.
When the scroll content is larger than the scroll view, people can scroll it by dragging, with a mouse wheel or trackpad, or you can drive it from an animation or [Data Binding](/docs/editor/data-binding/overview).

## Setting up scrolling
For step-by-step setup and every scroll setting, see [Scroll Constraint](/docs/editor/constraints/scroll-constraint). That page also covers:
* [Scrolling a list](/docs/editor/constraints/scroll-constraint#scrolling-a-list) built with [Data Binding lists](/docs/editor/data-binding/lists).
* [Adding a scroll bar](/docs/editor/constraints/scroll-constraint#adding-a-scroll-bar) that people can drag.
* [Snapping](/docs/editor/constraints/scroll-constraint#snap) to items as scrolling stops.
# Sizing and Positioning
Source: https://rive.app/docs/editor/layouts/sizing-and-positioning
Control how a Layout child sizes itself and where it sits within its parent.
In a Layout, the parent decides how its children are arranged, and each child decides its own size. This page covers the settings you set on a child: its width and height, size limits, margin, and whether it's positioned relative to its siblings or pinned to its parent's edges.
These settings apply to anything that participates in a Layout: other Layouts, and shapes, text, and images set to **Layout** in the **Inspector**. Component instances in **Layout** mode use the same width and height options. See [Component Sizing](/docs/editor/layouts/component-sizing).
For settings that control how a parent arranges its children, such as direction, padding, and gap, see [Arranging Children](/docs/editor/layouts/arranging-children).
## Width and height
A child's width and height each use one of three scale types: **Fixed**, **Hug**, or **Fill**. You can set width and height independently. For example, a button can hug its label horizontally while keeping a fixed height.
Select the scale type below the width and height fields in the **Inspector**.

[YouTube video player](https://www.youtube.com/embed/eOGfPV7zBbQ)
### Fixed
A Fixed width or height stays the same size regardless of the parent or the child's content. Enter a value in points, or use the unit toggle in the field to switch to a percentage of the parent's size.
Percentages are useful when a child should scale with its parent but you don't want it to take up all the available space, such as a panel that's always 50% of the screen width.
### Hug
A Hug width or height shrinks or grows to fit the child's own content. Use Hug when the content should determine the size, such as a button that grows with its label or a list that gets taller as items are added.
To Hug, a Layout needs content it can measure: child Layouts, text, or parametric shapes (rectangles, ellipses, triangles, polygons, and stars). If the Layout has nothing it can measure, the Hug option isn't available.
A Layout that hugs child Layouts always grows to fit them. Text and other content that Rive measures works differently: by default, a Hug child sized by that content stops growing at the edge of its parent, even if the content is larger. To let it grow to its full content size, select **Hug past bounds**. For example, a long block of text in a [scroll region](/docs/editor/layouts/scrolling) needs this option so it can grow taller than the visible area. This option appears when the width or height uses Hug. Min and max [size constraints](#size-constraints) still apply.
This tutorial uses Hug to build a button that resizes with its label:
[YouTube video player](https://www.youtube.com/embed/dx63jfWJtLQ)
> [!NOTE]
>
> An artboard can only Hug if it contains a relative Layout or a component instance in **Layout** mode.
### Fill
A Fill width or height expands to take up the space available in the parent. Fill is only available on relative children inside a Layout. Absolute children can't use Fill.
How Fill behaves depends on whether the axis runs in the same direction as the parent's arrangement:
* **Along the parent's direction:** In a Row parent, this is width. In a Column parent, it's height. The child shares the leftover space with its siblings that also use Fill. The amount is measured in `fr` (fill ratio) units.
* **Across the parent's direction:** In a Row parent, this is height. In a Column parent, it's width. The child stretches to the parent's full size, minus padding.
Fill ratios decide how siblings split the leftover space. Three children set to `1fr` each get an equal share of the leftover space. A child set to `2fr` gets twice the space of a child set to `1fr`.
Tip
**Example - A sidebar and content area**
A Row Layout with no padding or gap contains a sidebar and a content area, both set to Fill width with **Base size** set to `0` points. The sidebar is `1fr` and the content area is `3fr`, so the sidebar takes a quarter of the width and the content area takes the rest. When the Row gets wider, both grow in the same proportions.
When a child uses Fill along its parent's direction, the **Inspector** also shows a **Base size** field. The base size is the child's starting size before the leftover space is shared out. Set it in points or as a percentage, or leave it on auto to start from the size of the child's content.
> [!NOTE]
>
> With the base size on auto, siblings with the same fill ratio aren't always the same size. Each child starts from the size of its content, and only the leftover space is shared equally. For example, if three `1fr` children contain child Layouts of different sizes, the child with the largest content ends up the largest. To make them exactly the same size, set the **Base size** of each child to `0`.
## Aspect ratio
Use **Ratio** in the **Inspector** to lock a Layout's width and height to an aspect ratio. Enter a ratio as `16:9`, `16/9`, or a decimal such as `1.78`.
The **W**/**H** button at the end of the field picks the axis you size yourself. That axis keeps its scale type and value. The other axis is calculated from the ratio, and its controls become read-only. For example, lock **W** on a Fill-width card with a `16:9` ratio, and its height follows as the card gets wider.
If you pick an axis before entering a ratio, the ratio is taken from the Layout's current size.
## Size constraints
Size constraints set a minimum or maximum width or height. They're most useful with Hug and Fill, when you want a child to respond to its content or parent but only up to a point. For example, a text field can fill its row but stop growing at 400 points wide.
Click the icon above the absolute/relative toggle, then select **Min width**, **Max width**, **Min height**, or **Max height**. Like width and height, constraints can be set in points or percentages.

## Margin
Margin adds space outside a child, between it and its parent's edges or its siblings. Use the edge toggle to set margin on each side separately, and use the unit toggle to switch between points and percentages.
Margin is set on the child, unlike padding and gap, which are set on the parent. To add the same space between all of a parent's children, use the parent's gap instead of giving each child a margin. Margins on neighboring siblings add together, so two children with a 10-point margin are 20 points apart. See [Padding, gap, and margin](/docs/editor/layouts/arranging-children#padding-gap-and-margin).
## Relative and absolute positioning
A child is positioned in one of two ways:
* **Relative:** The parent places the child based on its direction, alignment, and gap. Relative children reflow when the parent resizes or when siblings are added or removed.
* **Absolute:** The child ignores the parent's arrangement and pins itself to the parent's edges. Absolute children don't take up space, so their siblings are arranged as if they weren't there.
Use absolute positioning for things that should stay in place while other content reflows, such as a close button in the corner of a dialog or a badge on a card.
Use the toggle at the top-right of the Layout section in the **Inspector** to switch between relative and absolute. The section's heading shows the current mode: **Position: Constrained by Parent** for a relative child, or **Position: Absolute** for an absolute one.

### Pinning to edges
An absolute child is pinned to at least two edges of its parent: one horizontal and one vertical. The distance from each pinned edge stays the same when the parent resizes.
To choose which edges to pin, select the markers in the position widget in the **Inspector**, or use the fields below it. Hold Shift while selecting a marker to pin a second edge on the same axis, such as both left and right. Distances can be set in points or as a percentage of the parent's size.
You can also choose the pinned edges from the horizontal and vertical constraint dropdowns below the position widget:
* **Left**, **Right**, **Top**, or **Bottom:** The child keeps its distance from that edge.
* **Left + Right** or **Top + Bottom:** The child keeps its distance from both edges, so its width or height stretches with the parent.
* **Scale:** The child keeps both distances as percentages of the parent, so its position and size scale with the parent.

Tip
**Example - A badge on a card**
A notification badge is an absolute child of a card, pinned 8 points from the top and 8 points from the right. When the card's content changes size, the badge stays in the top-right corner, and the card's other content is arranged as if the badge weren't there.
## Hiding a Layout
Click the eye button in the Layout section header to hide a Layout and take it out of its parent's arrangement. A hidden Layout takes up no space, so its siblings reflow to fill the gap. Click it again to show the Layout.
This is different from lowering opacity, which leaves the Layout in place and still taking up space. You can key the button in animate mode or bind it, for example to collapse a row when there's nothing to show.
## Computed transform
Layouts and constraints can move and resize an object, so its **Transform** values don't always match where it ends up. Expand the **Computed Transform** section in the **Inspector** to see the final world, artboard, and local position, and the final size of Layouts, text, and images. See [Computed Transform](/docs/editor/interface-overview/inspector#computed-transform) for each value.
The values are read-only, but you can bind them with [Target to Source](/docs/editor/data-binding/binding-data#target-to-source) to write them into a view model. For example, bind a Layout's computed width to a number property to read its size after layout in your app or in other bindings.
# Libraries
Source: https://rive.app/docs/editor/libraries
Share components, view models, and enums across Rive files in the same project.
> [!NOTE]
>
> Libraries are available on Voyager and Enterprise plans. [Learn more about our plans and pricing](https://rive.app/pricing?utm_source=docs\&utm_medium=content).
Libraries let you share [components](/docs/editor/fundamentals/components), [view models](/docs/editor/data-binding/view-models), enums, and [scripts and shaders](#sharing-scripts-and-shaders) across Rive files in the same project.
Publish the elements you want to share from a source file, then import them into other files. When you publish changes to the library, those files receive an update notification so you can choose which elements to update.
This gives your team a shared source for reusable elements, with version history to help you track changes.
[YouTube video player](https://www.youtube.com/embed/g6AXyqp4Ow0)
## Creating a library
Any Rive file can become a library. To publish one:
**Step 1**
Create a [component](/docs/editor/fundamentals/components), a [view model](/docs/editor/data-binding/view-models), or both. To turn an artboard into a component, select it on the stage and click the component icon in the inspector, or press `Shift` + `N`.
**Step 2**
Open the publish menu in the toolbar and select **To Library**, or select **Publish Library** from the file menu.
**Step 3**
In the publishing panel, check the components, view models, and enums to publish. Checking an element also checks the elements it depends on, and they stay checked while it is.

## Importing from a library
Click the **+** icon in the **Assets** or **Data** panel and select **Library Component**. The library panel opens beside the left sidebar and lists the libraries available to your file.
> [!NOTE]
>
> Currently, a Rive file can only access libraries contained within the same project. Cross-project — or workspace — libraries are coming soon. Public libraries are planned soon after that.
Select a library to see its components, view models, and enums. Choose the elements you want to import, then select **Add to File** or **Add to Active Artboard**.

> [!TIP]
>
> Use the version dropdown to browse and import earlier versions of a library.
>
> 
After importing, use the components from the **Assets** panel and view models from the **Data** panel. Imported elements have a small library icon in the bottom-right corner of their regular icon, as well a version number.

### Sharing scripts and shaders
Libraries can also share [scripts](/docs/scripting/getting-started) and [shaders](/docs/scripting/wgsl-shaders). When you publish, check them in the **Scripts & Shaders** section of the publishing panel.
To import them, open the library in the library panel and select the **Scripts** tab. It lists the scripts and shaders published in the selected version. Choose the ones you want, then select **Add to File**.
### Missing dependencies
Imported components can depend on other library components that aren't in your file yet. When that happens, select the library in the **Assets** panel. The inspector shows **Dependencies** as **Missing Dependencies**.
Click **Add Missing Dependencies** to import the library components they depend on.
## Library details
In the **Assets** panel, each library you've imported from appears as its own item. Inside it, elements keep the folders they're organized in within the library's own file.
Select a library in the **Assets** panel to see its details in the inspector:
* **Status**: whether the library is published. You can't import from an [unpublished library](#unpublishing-a-library), but files that already use it keep their components.
* **Latest Version**: the newest published version of the library.
* **Open Library File**: opens the library's source file.
* **View in Library Browser**: opens the library panel on this library so you can browse and import more.
## Updating a library
### Publish changes
Edit the source file to change, add, or remove components, view models, and enums. Then republish using **To Library** in the toolbar's publish menu or **Publish Library** in the file menu.
The publishing panel shows:
* **Version**: the current version and the version this update will publish.
* **Description**: optional change notes. Files that use the library see them when they update.
Files that have imported elements from the library display a badge when an update is available.
### Update imported elements
**Step 1**
In the file that uses the library, right-click the component in the **Assets** panel.
**Step 2**
Select **Library Options** > **Update Component**.
**Step 3**
Choose the library elements to update, then select **Update Selected**.
> [!NOTE]
>
> When you add a view model from a library to another file, Rive creates a unique instance of that view model in the Data panel. Its property values are independent of the library's defaults, even if the instance isn't used on an artboard.
>
> This prevents changes to library defaults from overwriting values you've customized in the host file.
### Sync view model instances
To sync instances with the library, right-click the view model in the **Data** panel and select **Library Options** > **Sync Instances**.
Syncing matches instances by name and:
* Adds any library instances that are missing from your file.
* Sets the default instance to match the library's default instance.
* Copies the library's values into properties that are still set to their type's default (for example, `0`, `false`, or an empty string).
Syncing never deletes instances. It preserves property values that differ from their type's default, but can replace default-valued properties even if you set them intentionally.
> [!NOTE]
>
> When you update a library, Rive automatically adds any new instances, but it doesn't change your file's default instance. Use **Sync Instances** if you also want the default instance to match the library's.
## Detaching
[YouTube video player](https://www.youtube.com/embed/TtOOPSAm6pI)
Detach an imported component or view model to make a local copy you can edit independently of the library.
Right-click the component or view model in the left sidebar and select **Library Options** > **Detach**. Rive copies its contents into your file and redirects any references to the local copy.
> [!NOTE]
>
> It's not possible to re-attach a component after it has been detached.
## Export options
Library components can depend on other elements, such as images or components from another library. Export options control which components and assets are included in the exported `.riv` file.
Select a component, asset, or library in the **Assets** panel to set its export options in the inspector.

| Option | Export behavior |
| - | - |
| **Automatic** | Include the asset or component if it's used somewhere on the stage. For assets within a library, this option is inherited from the source file. |
| **Force Export** | Include the asset or component even if it isn't referenced in the file. |
| **Prevent Export** | Exclude the asset or component even if it's referenced in the file. |
Choose export options based on how you'll use the file at runtime. For example:
* If you supply an image from an external source at runtime, exclude it from the `.riv` file.
* If you share a library component across multiple Rive files through data binding, export it separately and exclude it from the files that use it to avoid duplication.
> [!NOTE]
>
> Currently, the export behavior for assets within a library component can only be set at the library level, not per component. To do so, set the panel display mode to Source/Type, and select the library item in the asset panel.
## Unpublishing a library
Select **Unpublish Library** from the file menu to stop additional files from accessing the library.
Files that have already imported library components keep those components and retain access to previously published versions. You can republish the library at any time.
# Bones
Source: https://rive.app/docs/editor/manipulating-shapes/bones
Bones create a skeleton you can use to pose and animate elements. Connect bones in a chain, then move or rotate them to control anything from a character’s arm to a bending branch or waving flag.
> [card] [Learn by remixing](https://rive.app/community/files/28327-mesh-and-bones/?utm_source=docs\&utm_medium=docs_link_card\&utm_campaign=docs_to_marketplace_links)
>
> Open this file on Marketplace, then click Remix to experiment in the Rive Editor.
Bones can control elements in three ways:
* **Transform an element:** Make a shape, image, group, or other element a child of a bone. The entire element follows the bone’s position, rotation, and scale.
* **Deform a vector:** Bind the vertices and Bézier handles of a vector path to one or more bones. Adjust their weights to control how the path bends.
* **Deform an image:** Add a mesh to a raster image, then bind its vertices to one or more bones. Weighted vertices allow the image to bend and stretch smoothly.
You can combine these methods in the same rig. For example, a character’s hand might be parented to an arm bone while the sleeve’s vertices are weighted across several bones to create a natural bend.
[YouTube video player](https://www.youtube.com/embed/WDILxfmCEt0)
## Creating Bone chains
Select the Bone tool from the **Bones** menu, or press **B**.
Click once to place the start of the first bone, then click again to set its length and rotation. Continue clicking to add bones to the chain. Each new bone becomes a child of the previous bone.
Press Esc or switch to the **Select** tool (**V**) when you’re finished.

To extend an existing chain from a different point, select the [joint](#joints) where you want the new branch to begin. Then select the Bone tool and continue clicking to add bones.

> [!TIP]
>
> If you can’t see your bones on the Stage, open **View Options** and make sure **Bones** is enabled.
### Joints
Joints are the points where bones connect. Use them to position and orient bones while building your chain.
Joints do not appear as separate objects in the Hierarchy. Moving a joint changes properties such as the length and rotation of the bones connected to it.
### Root bone
The first bone in a chain is the **root bone**. It controls the position of the entire chain and is the only bone in the chain with X and Y position properties. Every other bone is positioned by its length and rotation relative to its parent.
To move the whole chain, drag the root joint at the start of the root bone.
## Controlling elements with Bones
### Transforming elements
Make an element a child of a bone to control its transform. When the bone moves, rotates, or scales, its children follow without being deformed.
To connect an element, drag its layer onto the bone in the Hierarchy. You can parent shapes, images, groups, and other bone groups to a bone.
This method works well for rigid parts that should keep their shape, such as a hand, shoe, or mechanical component.
[YouTube video player](https://www.youtube.com/embed/g8MWMKixURo)
### Deforming elements
You can bind bones to the control points of both vector paths and raster images:
* Vector paths use vertices and Bézier handles.
* Raster images use the vertices of a [mesh](/docs/editor/manipulating-shapes/meshes).
Binding allows different bones to influence different parts of an element, creating smooth bends and other deformations.
> [!NOTE]
>
> Before binding a shape, such as a rectangle or ellipse, convert it to a custom path. Select its path layer, then press `Enter`.
**Step 1**
Select the element you want to deform, such as a vector shape or a raster image with a [mesh](/docs/editor/manipulating-shapes/meshes).
**Step 2**
In the **Bind Bones** section of the Inspector, click the **+** button.
**Step 3**
Hold **Cmd + Shift** on macOS or **Ctrl + Shift** on Windows, then select the bones you want to bind.
**Step 4**
Click **Done**.
After binding, Rive assigns each bone a color. The same colors appear on the bone and in the Bind Bones section, helping you identify which bones influence each control point.
Rive automatically assigns an initial influence, or weight, to each vertex. Vector paths also allow you to weight their Bézier handles. Adjust these weights to fine-tune how the element deforms.
#### Adjusting vertex weights
A weight determines how much influence a bone has over a vertex. A vertex can be influenced by one or more bound bones, but its combined weights always equal 100%.
After binding, each vertex displays a pie chart using the colors assigned to its bones. The size of each colored segment represents how much that bone influences the vertex.
Rive assigns initial weights automatically. To adjust them, select a vertex or group of vertices, then change the weight for each bone in the Bind Bones section of the Inspector.
Vertices near a joint often benefit from being influenced by both neighboring bones. Blending their weights creates a smoother bend as the bones move.
> [!NOTE]
>
> On vector paths, you can weight a vertex and its Bézier handles independently for more precise control over the deformation.
>
> 
>
> [Try it in the Rive Editor](https://rive.app/community/files/28349-control-bezier-handles-with-bones?utm_source=docs\&utm_medium=docs_link_card\&utm_campaign=docs_to_marketplace_links).
You can lock a vertex’s weight for a specific bone. Locked weights stay fixed when you adjust other bone weights on the same vertex.
#### Weight editing tools
Rive includes tools to help you adjust vertex weights after bones are bound.
**Edit Weights** lets you adjust the influence of a specific bone on selected vertices. Select a vertex, then select a bone on the Stage or in the **Bind Bones** section. Drag up or down on the vertex to increase or decrease that bone’s weight.
**Smooth** evens out bone weights across neighboring vertices. If vertices are selected, smoothing applies to the selected vertices. If no vertices are selected, it applies to the entire shape.
**Auto-Weights** automatically assigns weights based on each vertex’s nearest bone, blending where neighboring bone regions meet. If vertices are selected, auto-weights apply to the selected vertices. If no vertices are selected, they apply to the entire shape.
Auto-Weights includes two settings:
* **Blend** - controls how widely weights blend at the boundary between two bones. Higher values spread the blend across more of the mesh, creating softer deformation. Lower values create a more rigid result, where each vertex sticks more closely to its nearest bone.
* **Influences** - controls the maximum number of bones, from 1 to 4, that can influence each vertex.
#### Mesh view options
**Show Weights** shows or hides weight pie charts on unselected vertices. Selected vertices always show their weights while you edit them.
> [!NOTE]
>
> For other mesh view options, such as isolating the mesh or showing and hiding triangles, see [Meshes](/docs/editor/manipulating-shapes/meshes#mesh-view-options).
# Clipping
Source: https://rive.app/docs/editor/manipulating-shapes/clipping
Hide everything outside a shape, or cut a hole in your graphics with inverse clipping.
Clipping hides the parts of an object that fall outside another shape, called the clip source. Use it to crop graphics to a frame, reveal an object as a shape moves over it, or keep content inside a container.
You can clip a shape, a group, or any other object on the stage. Clipping a group clips everything inside it.
> [!NOTE]
>
> To hide everything outside an artboard's bounds, you don't need a clip source. Turn on the artboard's [Clip](/docs/editor/fundamentals/artboards#clip) option instead. This is mostly useful for artboards used as [components](/docs/editor/fundamentals/components), since content outside a top-level artboard isn't rendered at runtime.

[YouTube video player](https://www.youtube.com/embed/bxmipy1Gv6Y)
## Adding a clip
**Step 1**
Select the object you want to clip.
**Step 2**
In the **Clip** section of the Inspector, click **+**. A blue border appears around the stage while Rive waits for you to pick a clip source.
**Step 3**
Click the shape or group you want to clip with, on the stage or in the Hierarchy.
**Step 4**
Hide the clip source by clicking its eye icon in the Hierarchy, so it doesn't cover the graphics it's clipping. The clip still works while the source is hidden.
To change the source later, click the target button on the clip and pick a different shape or group.
### What can be a clip source
A clip source can be a shape or a group, but not an artboard. When the source is a group, every shape inside it is combined into one clip.
The clip follows the filled area of each shape, including any path effects such as a [trim](/docs/editor/manipulating-shapes/trim-path), and ignores strokes. A shape with only a stroke doesn't clip anything.
### Using more than one clip
You can add as many clips to an object as you want. Only the parts of the object that fall inside every clip are drawn.

### Turning a clip on and off
Click the eye icon on a clip in the Inspector to turn the clip off without removing it. You can key this toggle on a timeline or [bind it to data](/docs/editor/data-binding/overview) to switch clipping on and off while your graphic runs.
## Fill rule and path direction
Each clip has a fill rule, set from the dropdown on the clip in the Inspector. It decides which areas count as inside when the source has overlapping paths, or paths inside other paths. It works like a [fill's fill rule](/docs/editor/fundamentals/fill-and-stroke#fill-rules), but it's set separately: the source shape's own fill rule doesn't affect the clip.
* **Non-zero** is the default. Whether an overlapping area is inside depends on the direction each path is drawn in.
* **Even-odd** alternates: an area inside one path is inside the clip, an area inside two is outside, and so on. Use it to cut holes. See [Inverse clipping](#inverse-clipping).

If a shape clips only partly, or not at all, check the direction of its paths. With **Non-zero**, paths drawn in opposite directions cancel each other out where they overlap. Reversing the direction of a path usually fixes this. **Even-odd** won't help here, since it always treats overlapping areas as outside.
## Inverse clipping
Inverse clipping does the opposite of a normal clip: it hides the graphics inside a shape and shows everything outside it.

To do this, clip with a shape that has a hole in it: a large rectangle with the hole's path inside it.

**Step 1**
Draw a rectangle that covers the area you want to keep, such as the whole artboard.
**Step 2**
Draw the shape of the hole, such as an ellipse. In the Hierarchy, move its path into the same shape as the rectangle's path.

**Step 3**
Select the object you want to clip, add a clip, and pick the shape you just made as its source.

**Step 4**
Set the clip's fill rule to **Even-odd**, so the area inside both paths is cut out.

**Step 5**
Hide the clip source so it doesn't cover your graphics.
> [!TIP]
>
> The shape's own fill doesn't affect the clip, but it can help you see what you're building. To show the hole on the stage while you work, set the shape's fill rule to **Even-Odd** in its fill options.
>
> 
## Performance
Clipping adds rendering work. Rive first draws the clip source, then checks every pixel of every clipped object against it. The more objects a clip covers, and the more area they fill, the more work it adds.
* **Use a fill rule instead of a clip when you can.** To cut a hole in a single shape, put the hole's path inside the shape and set the shape's fill rule to **Even-Odd**, or reverse the hole's path direction. This costs nothing extra. Save inverse clipping for when the hole needs to cut through other objects.
* **Clip only what needs it.** A clip on one small group costs less than a clip that covers everything in the artboard.
* **Share one clip.** Clipping a group once is cheaper than giving each object inside it its own clip.
* **Rectangles are cheaper.** Clipping to a rectangle that isn't rotated, such as an artboard's bounds or a Layout without rounded corners, takes a faster path than clipping to an ellipse, a star, or any other shape.
# Effect Groups
Source: https://rive.app/docs/editor/manipulating-shapes/effect-groups
Share one stack of path effects, such as trim, dash, or scripted effects, across many fills and strokes, and control them from one place.
An Effect Group holds a stack of path effects, such as a [trim or dash](/docs/editor/manipulating-shapes/trim-path) or a [scripted path effect](/docs/scripting/protocols/path-effect-scripts), that you can apply to any number of fills and strokes. Every fill and stroke that uses the group gets the same effects, and changing or animating the group updates all of them at once.
Use an Effect Group when several shapes need to behave the same way, such as many lines that draw on together, or a set of icons that share one dash pattern. Without one, you'd add and animate the same effect on each fill or stroke separately.
[YouTube video player](https://www.youtube.com/embed/18LrObHLRFQ)
## Creating an Effect Group
**Step 1**
In the toolbar, open the **Stage Control Tools** menu and select **Effect Group**.
**Step 2**
Click the stage to place the Effect Group. It appears in the Hierarchy. Its position only affects where it sits on the stage, not the effects.
**Step 3**
With the Effect Group selected, click **+** in the **Path Effects** section of the Inspector, and add the effects you want: **Trim Effect**, **Dash Effect**, another **Effect Group**, or a scripted path effect.
**Step 4**
Set each effect's options. Effects are applied in the order they appear in the stack.
## Applying an Effect Group
You can apply an Effect Group to many shapes at once from the Hierarchy, or to a single fill or stroke from its options. An Effect Group can only be used by shapes on the same artboard.
### To shapes in the Hierarchy
**Step 1**
Select the shapes in the Hierarchy.
**Step 2**
Right-click and select **Add Group Effect**, then select the Effect Group.
The Effect Group is added to every fill and stroke of the selected shapes. To take it off again, right-click the shapes and select **Remove Group Effect**.
### To a single fill or stroke
**Step 1**
Open the options for the fill or stroke.
**Step 2**
In the **Path Effects** section, click **+** and select **Effect Group**.
**Step 3**
Choose the Effect Group from the dropdown.
An Effect Group sits in a fill or stroke's effect stack like any other effect, so you can combine it with that fill or stroke's own effects.
## Animating an Effect Group
Key the effects inside the Effect Group, such as a trim's **Start** and **End**, and every fill and stroke that uses the group animates together. To change the animation later, you only need to edit one set of keys.
## Nesting Effect Groups
An Effect Group can contain other Effect Groups. Use this to build a shared base effect, then extend it for some shapes. An Effect Group can't contain itself, directly or through another group.
# Joysticks
Source: https://rive.app/docs/editor/manipulating-shapes/joysticks
Create reusable controls for complex animations
Joysticks let you control complex poses and deformations with a single handle. Use them to combine multiple animated properties into reusable controls, such as moving a character's eyes and head together.
Each joystick axis controls the playback position of an assigned timeline. Moving the handle scrubs through those timelines, and you can key its position to animate the resulting poses.
[YouTube video player](https://www.youtube.com/embed/PvZYDAUnLXE)
## Creating a new Joystick
To create a new joystick, either find the Joystick Tool in the Stage Controls Tool menu, or by hitting the J key. Once the tool is activated, click anywhere on the stage to add a new Joystick.

> [!TIP]
>
> If joysticks aren't visible on the stage, open the **View Options** menu and make sure **Joysticks** is enabled.
## Joystick properties
With the Joystick selected, you’ll see a number of properties that you can use in the Inspector.
### Handle
The Handle X and Y property describes the position that the handle is currently in. You’ll notice that these properties update as you move the handle around the Joystick.

### Position
The position property describes the position of the Joystick on the stage.
### Size
The size property describes the size of the joystick. We can modify this property to fit our needs by making the joystick longer/shorter or wider/skinnier.

### Origin
The origin property sets which point of the joystick sits at its position. Values are relative to the joystick's size: `0, 0` is the top-left corner, `1, 1` is the bottom-right corner, and the default `0.5, 0.5` is the center.
Changing the origin moves the joystick's bounds around its position without changing how the handle maps to the assigned timelines. For example, set the origin to `0, 0.5` to make a slider extend to the right of its position instead of centering on it.
### Draw in World Space
This toggle tells the joystick whether the joystick will scale with the zoom level or not. This option is useful when we need the joystick to always stay the same size, relative to the artboard.
### X & Y dropdown
The X & Y dropdowns allow us to assign timelines to the different axis of the Joystick.
For example, this timeline animates the 3D rotation of this ship. You'll notice many keys, which would make reusing this animation within other animations tricky to achieve.

When the timeline is assigned to the X axis of the Joystick, notice that the joystick becomes a slider that only allows you to move the handle in the X direction.

**Invert Toggle**
After you add a timeline to an axis, you’ll notice a toggle that appears next to it. This allows you to invert the direction that the joystick scrubs through the timeline.

### Handle source
The handle source allows you to constrain the position of the handle to another object's position properties. Use the button, then select an object you'd like to use as the handle's position source. This option is helpful when you want the mouse cursor to drive the joystick while the state machine is running.

# Rigging Overview
Source: https://rive.app/docs/editor/manipulating-shapes/manipulating-shapes
Set up your graphics so they bend, follow each other, and can be posed with simple controls, using bones, meshes, joysticks, and constraints.
Rigging is the setup you do before animating, so the animating itself is easier. Instead of keying every vertex of an arm or every feature of a face, you build controls that move many things at once, then animate those controls.
A rig can be as simple as one object following another, or a full character with a skeleton, bending limbs, and a handle that turns its head. Most rigs combine several of these tools:
> [card] [Bones](/docs/editor/manipulating-shapes/bones)
>
> Build a skeleton that moves objects as a hierarchy, and bend vector paths and images by binding them to bones.
> [card] [Meshes](/docs/editor/manipulating-shapes/meshes)
>
> Add vertices to a raster image so you can warp it, or bind it to bones so it bends.
> [card] [Joysticks](/docs/editor/manipulating-shapes/joysticks)
>
> Blend timelines with a single handle, to pose a head, eyes, or face from one control.
> [card] [Constraints](/docs/editor/constraints/constraints-overview)
>
> Make an object follow, aim at, or copy another, without keying it.
## Choosing a tool
| To do this | Use |
| - | - |
| Move parts of a character together, like an arm and hand | [Bones](/docs/editor/manipulating-shapes/bones) |
| Bend a vector shape, like a sleeve or a tail | [Bones](/docs/editor/manipulating-shapes/bones#deforming-elements) bound to the path's vertices |
| Bend or warp an image | A [mesh](/docs/editor/manipulating-shapes/meshes), on its own or bound to bones |
| Reach a target with a limb, like a foot on the ground | An [IK constraint](/docs/editor/constraints/ik-constraint) |
| Keep an object within a distance of another, or on a path | A [distance](/docs/editor/constraints/distance-constraint) or [follow path](/docs/editor/constraints/follow-path-constraint) constraint |
| Copy another object's position, rotation, or scale | A [translation](/docs/editor/constraints/translation-constraint), [rotation](/docs/editor/constraints/rotation-constraint), [scale](/docs/editor/constraints/scale-constraint), or [transform](/docs/editor/constraints/transform-constraint) constraint |
| Pose a face or turn a head with one control | A [joystick](/docs/editor/manipulating-shapes/joysticks) |
| Make Layout content scrollable | A [scroll constraint](/docs/editor/constraints/scroll-constraint) |
# Masks
Source: https://rive.app/docs/editor/manipulating-shapes/masks
Hide parts of an object using the pixels of another object, with alpha and luminance mask modes.
A mask hides parts of an object using another object, called the mask source. Use masks for soft reveals, fades, and cutouts that follow the transparency or brightness of another graphic.
Masks work like [clipping](/docs/editor/manipulating-shapes/clipping), with one difference: a clip uses the source's shape, while a mask uses the source's pixels. That means a mask follows the source's transparency or brightness, not just its outline.
> [!NOTE]
>
> Masks require GPU Canvas in every runtime. See [Feature Support](/docs/feature-support).
## Adding a mask
You can mask a shape, a group, a layout, or any other object on the stage, except a path or an artboard. Masking a group masks everything inside it.
**Step 1**
Select the object you want to mask.
**Step 2**
In the **Mask** section of the Inspector, click **+**.
**Step 3**
Click the shape, group, or layout you want to use as the mask source.
By default, the mask source is used only as the mask and doesn't draw on its own, so you don't need to hide it. See [Drawing the mask source](#drawing-the-mask-source).
An object can have more than one mask. Each mask gets its own card in the **Mask** section.
## Choosing a mask source
The first row of a mask's card shows its source. Hover it to highlight the source on the stage, or click it to pick a different one.
A mask source can be a shape, a group, or a layout on the same artboard. It can't be:
* A path on its own. Pick the shape that contains it instead.
* An artboard.
* The masked object itself, anything inside it, or its parent.
When you select an object that's used as a mask source, the **Target For** section of the Inspector shows which object it masks.
If a mask has a warning icon next to its source, the mask isn't being applied. This happens when the source has been moved inside the object it masks, or when a [Draw Order Rule](/docs/editor/animate-mode/animating-draw-order#draw-order-rules) splits the masked object. Hover the icon to see which one.
## Mask modes
The **Mode** dropdown sets which part of the source's pixels decides what shows:
* **Alpha**: Opaque areas of the source show the object, and transparent areas hide it. This is the default.
* **Inverted Alpha**: Transparent areas of the source show the object, and opaque areas hide it. Use it to cut a hole in an object.
* **Luminance**: Bright areas of the source show the object, and dark areas hide it.
* **Inverted Luminance**: Dark areas of the source show the object, and bright areas hide it.
For example, mask an image with a shape whose fill is a white-to-transparent gradient in **Alpha** mode to fade the image out, or use a black-and-white image as the source in **Luminance** mode.
## Turning a mask on and off
Click the toggle at the end of the **Mode** row to turn a mask on or off without removing it. To remove a mask, click its minus icon.
The on and off state, the mode, and **Draw Source** can each be keyed on a timeline and [bound to data](/docs/editor/data-binding/overview), so you can switch a mask on or change its mode during an animation.
## Drawing the mask source
**Draw Source** is off by default, so the source is used only as the mask. Turn it on to also draw the source normally, for example when the source is a visible part of your design that should also mask another object.
## Custom bounds
By default, Rive measures the mask's region from the source's content. Turn on **Custom Bounds** to set the region by hand with its **Position** and **Size**. Use it to crop a mask to a region, or for content that can't report where it paints, such as a [scripted drawable](/docs/scripting/protocols/node-scripts).
When you turn on **Custom Bounds**, the region starts at the area Rive measured, so the mask looks the same until you change it.
## Resolution
**Resolution** sets how sharp the mask is, as a multiple of its size. The default is **1x**. Higher values make the mask crisper, but use more memory.
# Meshes
Source: https://rive.app/docs/editor/manipulating-shapes/meshes
Add natural, organic deformations to raster graphics.
Meshes let you deform raster images and [components](/docs/editor/fundamentals/components#deform) by moving vertices instead of transforming the image as a flat rectangle. They are useful for natural motion, such as skin flexing, fabric rippling, hair flowing, or creating faux 3D effects.
A mesh is built from a [contour](#contours), which defines the mesh’s shape and vertices. Rive uses that contour to create a triangulated surface over the image.
## Adding a Mesh to an element
Meshes can be applied to images, as well as instances of components with their **Mode** set to **Node**
### Images
**Step 1**
Select an image on the Stage or Hierarchy and press **Enter** or go to the **Deform** section in the Inspector.
**Step 2**
Click the **+** button and select **Mesh**.

### Components
You can also add a mesh to a [component](/docs/editor/fundamentals/components#deform) instance with **Mode** set to **Node**. The component draws its artboard as a flat image and the mesh deforms that image, so you can bind it to bones and animate its vertices like any other mesh.
**Step 1**
Select the component instance and set **Mode** to **Node**.
**Step 2**
In the **Deform** section of the Inspector, click **+** and select **Mesh**.
## Deforming a Mesh
Enter Mesh Editing Mode by pressing `V` or by deselecting **Edit Contour**.
In mesh editing mode, moving a vertex changes the shape of any triangles connected to that vertex and deforms the pixels inside those triangles. Pixels in triangles that are not connected to the moved vertex are not affected.
Here’s a simple mesh with four vertices divided into two triangles:
Here’s a slightly more complex mesh with a center vertex, dividing the image into four triangles:
The position of these vertices can be keyed on a timeline or [controlled by bones](/docs/editor/manipulating-shapes/bones).
In Animate mode, the Inspector has two buttons for keying vertices on the current frame:
* **Key All Vertices** keys the position of every vertex in the mesh.
* **Key Selected Vertices** keys the position of only the selected vertices.
## Contours
The contour defines the visible shape and vertex structure of the mesh. Editing the contour changes the mesh structure without deforming the image.
### Creating contours
When you add a mesh to an image, Rive automatically creates a simple contour with four vertices that make two triangles. You can use this contour as a starting point or make your own.
#### Manually create a new contour
Click the **New Contour** button to draw a new contour from scratch.
This is useful when the default contour does not match the shape of the image, or when you want full control over the mesh structure.
#### Auto-trace a new contour
Use **Auto-Trace** to quickly create a contour that follows the visible shape of an image.
Adjust the settings to control the generated contour:
* **Detail** - how closely the contour follows small details in the image.
* **Concavity** - how deeply the contour follows inward curves.
* **Uniform** - how evenly vertices are spaced along the contour.
* **Alpha** - the transparency threshold used to detect the image edge.
* **Padding** - extra space added around the traced outline.
#### Contour bounds
Only the area inside the contour is rendered. Anything outside the contour is hidden.
This can be useful when you want to create multiple meshes from different parts of the same image.
### Editing contours
Use **Edit Contour** or press **P** to adjust the existing contour. The Mesh Pen lets you add new vertices or move existing vertices without warping the image.
Click continuously to create forced edges between vertices. Press **Esc** between clicks to create separate vertices and let Rive automatically generate the edges between them.
To connect two existing contour vertices with a forced edge, click one and then the other. To delete a contour vertex, hold **Alt** (**Option** on macOS) and click it.
#### Forced edges
Forced edges are edges you manually add between mesh vertices. Use forced edges when you need more control over the mesh structure, such as defining an important seam, crease, corner, or area where the mesh triangles should follow a specific path.
When using the Mesh Pen, click continuously to create connected vertices with forced edges.
Tip
**Example - Rigging a Snake**
In this example, the default edges made the snake stretch in an unexpected way, creating a bump in its skin. By adding a forced edge, the edges run perpendicular to the body, helping the snake deform more naturally.
Forced edges are shown as thicker lines in the mesh.

To remove a forced edge, select **Edit Contour**, then **Cmd-click** the edge on macOS or **Ctrl-click** the edge on Windows.
### Generate
Use **Generate** to add more vertices to the current mesh. Click **Generate** multiple times to increase the mesh complexity.
A more complex mesh can create smoother deformations, but it can also be harder to edit.
### Resetting a contour
Use **Reset** to return the mesh to its default contour.
## Managing meshes
### Naming
A mesh you haven't named takes the name of the image or component it deforms. For example, the mesh on "Arm" is named "Arm Mesh". Renaming the image renames the mesh, but a name you give the mesh stays.
In the timeline, keyed meshes appear under their image or component's row.
### Copying a Mesh
You can copy a mesh and apply it to another image.
**Step 1**
In the Hierarchy, select the mesh you want to copy and press **Cmd + C** on macOS or **Ctrl + C** on Windows.
**Step 2**
Select the image you want to apply the mesh to and press **Cmd + V** on macOS or **Ctrl + V** on Windows to paste the mesh.
### Swapping images
A mesh can continue to work when the image is changed.
This is useful when multiple images share the same basic structure. The same mesh can deform each face without creating a separate mesh for every image.
### Removing a Mesh
After an image has a mesh, the **Deform** section shows options for editing or removing it.
**Step 1**
Select an image on the Stage or Hierarchy and press **Enter** or go to the **Deform** section in the Inspector.
**Step 2**
Click the **Edit Mesh** or **Remove Mesh** button.
> [!WARNING]
>
> Removing a mesh deletes the mesh and its vertex edits from the image.
## Mesh view options
Mesh view options control how the mesh and image appear while editing. These options can make it easier to focus on vertices, edges, weights, or the deformed result.

* **Bounding Box Edit** - show a bounding box around selected vertices so you can transform them together.
* **Isolate** - show only the graphic or graphics being edited.
* **Show Weights** - show mesh weights while editing.
* **Deform** - toggle between the deformed and undeformed version of the image.
* **Show Triangles** - show or hide the triangle edges. When disabled, only vertices are shown.
* **Dim** - dim the image so the mesh is easier to see.
# Solos
Source: https://rive.app/docs/editor/manipulating-shapes/solos
Show one object at a time from a group, to switch between skins, rigs, layouts, or frames.
A Solo is like a group, but only one of its children is visible at a time, called the active child. Use it to switch between versions of something, such as hats on a character, views of a rig, or frames of an animation.
Switching a Solo is cheaper than animating the opacity of each object. The inactive children aren't drawn or updated at all.
[YouTube video player](https://www.youtube.com/embed/diYNK8aidaE)
## Creating a Solo
* **From a selection**: Select objects in the Hierarchy, right-click, and choose **Wrap in** > **Solo**.
* **From a group**: Right-click a group and choose **Convert to Solo**.
* **With the Solo tool**: Select the **Solo** tool from the **Arrangement Tools** menu in the toolbar (or press `S`), click the stage, then drag objects into the Solo in the Hierarchy.

## Choosing the active child
Click the radio button next to a child in the Hierarchy, or choose it from **Active** in the Inspector.
Some children aren't options and are always applied, such as constraints and clipping shapes.
## Animating a Solo
In a timeline, click a child's radio button to key the active child. The Solo switches instantly at each key.

To switch the active child from your app, [bind](/docs/editor/data-binding/overview) the Solo's **Active** property. See [Controlling Solos with enums](/docs/editor/data-binding/enums#controlling-solos-with-enums).
## Examples
### Skins
Put each version of a part in its own Solo to build swappable skins.

### Switching rigs
Rig a character from several angles, put each rig in a Solo, and switch between them as the character turns.

### Frame-by-frame animation
Put each frame in a Solo and key the active child on each frame of the timeline.

# Trim and Dash
Source: https://rive.app/docs/editor/manipulating-shapes/trim-path
Draw only part of a path with a trim, or break it into dashes and gaps, and animate either one.
Trim and Dash are path effects. They change which parts of a path a stroke or fill draws, without changing the shape itself. They're most often used on strokes:
* **Trim** draws only part of the path. Animate it to make a line draw on, draw off, or travel along a path.
* **Dash** breaks the path into a repeating pattern of dashes and gaps. Animate its offset to make the dashes march along the path.
## Adding a trim or dash
**Step 1**
Select the shape, then click the options button on the stroke or fill in the **Fills and Strokes** section of the Inspector.
**Step 2**
Open the **Effects** tab.
**Step 3**
In **Path Effects**, click **+** and select **Trim Effect** or **Dash Effect**.
Each stroke and fill has its own effects, and you can stack more than one. To share the same trim or dash across many shapes, put it in an [Effect Group](/docs/editor/manipulating-shapes/effect-groups).
## Trim
### Start and end
**Start** and **End** set which part of the path is drawn, as a percentage of the path's length. Only the section between them is visible. Key them on a timeline to animate the trim, for example from an **End** of 0% to 100% to draw a line on.

### Offset
**Offset** moves the visible section along the path, keeping its length the same. Animate it to make a segment travel around a shape.

### Sequential and Synced
When a shape has more than one path, the trim's mode decides how they're trimmed:
* **Sequential** treats the paths as one long path, trimming them one after another in their order under the shape.
* **Synced** trims every path at the same time, by the same percentage.


Set the mode to **None** to remove the trim.
## Dash

### Dashes and gaps
A dash starts with one **Dash** length. Click **Add gap** to add a gap after it, then **Add dash** to add another dash, building up a pattern that repeats along the path. Each length can be in pixels or a percentage of the path's length.

### Offset
**Offset** moves the dash pattern along the path, in pixels or a percentage. Animate it to make the dashes travel along the path.

# Actions
Source: https://rive.app/docs/editor/state-machine/actions
Set view model properties, report events, move focus, and more when a state starts or ends, a transition happens, or a listener fires.
An action does something in response to the state machine, such as setting a view model property or reporting an event. Actions can run from three places:
* **[States](/docs/editor/state-machine/states)**: when the state starts or ends.
* **[Transitions](/docs/editor/state-machine/transitions)**: when the transition starts or ends.
* **[Listeners](/docs/editor/state-machine/listeners)**: when the listener fires.
The same action types are available in all three. You can add as many actions as you need, and you can [data bind](/docs/editor/data-binding/overview) the values they use.
[YouTube video player](https://www.youtube.com/embed/4Uuu0MkBawE)
## Action types
| Action | What it does |
| - | - |
| **View Model Change** | Sets a [view model](/docs/editor/data-binding/overview) property. See [View Model Change](#view-model-change). |
| **Input Change** | Sets a legacy state machine [input](/docs/editor/state-machine/inputs). Use View Model Change for new work. |
| **Align Target** | Moves an object to the pointer. See [Align Target](#align-target). |
| **Focus** | Moves keyboard [focus](/docs/editor/accessibility/focus). See [Focus](#focus). |
| **Report Event** | Fires a [Rive event](/docs/editor/events/overview). |
| **Scripted Action** | Runs a [listener action script](/docs/scripting/protocols/listener-action-scripts). |
### View Model Change
Sets a view model property to a new value. Use **Set To** to choose where the value comes from:
* **A view model property**: Copies that property's value.
* **A listener value**: Uses something from the event that fired the listener, like the pointer position or a key. Only available in listener actions.
* **Value**: A fixed value you enter.
### Align Target
Moves the target object to the pointer's position. Use it to make an object follow the pointer, such as a custom cursor or a slider handle.
* **Target**: The object to move.
* **Preserve offset**: Keeps the object's distance from the pointer when the action starts, instead of snapping its origin to the pointer.
### Focus
Moves [focus](/docs/editor/accessibility/focus) between focusable elements. Choose a mode:
* **target**: Focuses a specific element.
* **traverse**: Moves focus in a direction: **next**, **previous**, **up**, **down**, **left**, or **right**.
* **clear**: Removes focus.
## Adding an action to a state or transition
**Step 1**
Select the state or transition in the graph.
**Step 2**
In the panel below the graph, click **+** next to its name and choose an action type.
**Step 3**
Choose when the action runs: at **enter** or at **exit**.
* For a state, **enter** runs when the state starts and **exit** runs when the layer leaves it.
* For a transition, **enter** runs when the transition starts and **exit** runs when it finishes.
**Step 4**
Configure the action.

## Adding an action to a listener
**Step 1**
Select the listener in the **Listeners** panel.
**Step 2**
In the panel below the graph, click **+** and choose an action type.
**Step 3**
Configure the action.
Listener actions run every time the listener fires.
# Listeners
Source: https://rive.app/docs/editor/state-machine/listeners
Respond to interactions, property changes, and events in your Rive file.
Listeners let you respond to interactions, property changes, and other events in your Rive file. When a listener is triggered, it can perform actions such as updating property values, firing Rive events, or running other logic.
A listener has three main parts:
* [Target](#target): what the listener watches
* [Listen to](#listen-to): what needs to happen to trigger the listener
* [Action](#listener-actions): what happens in response
Use listeners to create dynamic experiences that react to user input and changes in state.
[YouTube video player](https://www.youtube.com/embed/RBQdLRXNVbE)
## Creating a listener
**Step 1**
Select the element you want the listener to respond to.
> [!NOTE]
>
> To listen for a view model property change or Rive event, select the artboard or nested component instead.
**Step 2**
In the **Animations** panel, click the icon next to the **State Machine** to show listeners.
**Step 3**
Click the **+** icon to create a new listener and select the action the listener should perform.
Choose **Blank** to create a listener with no actions, or **Folder** to add a folder for organizing your listeners.
**Step 4**
With the listener selected, set its **Target**, **Listen to**, and other options in the right sidebar.
## Target
The **Target** determines what the listener watches. The target can be an element in your scene, an artboard, or a nested component.
Use an element as the target when you want to listen for interactions on that element, such as clicks or drags. Use an artboard or nested component as the target when you want to listen for view model property changes, Rive events, or other events that belong to that artboard or component.
### Opaque Target
**Opaque Target** controls whether pointer events stop at this listener's hit area or continue through to elements behind it.
When **Opaque Target** is enabled, pointer events stop at the target. When it's disabled, pointer events can pass through the target and trigger other listeners underneath.
## Listen to
**Listen to** is the condition the listener watches for. When the condition is met, the listener is triggered.
| Listen to | Description |
| - | - |
| [View Model Change](#view-model-change) | Fires whenever the selected view model property changes. |
| [Rive Event](#rive-event) | Fires when the selected Rive event is fired. |
| **Pointer Enter** | Fires when the pointer enters the target area. |
| [Pointer Exit](#pointer-exit) | Fires when the pointer leaves the target area. |
| **Pointer Move** | Fires repeatedly while the pointer moves over the target area. |
| **Pointer Down** | Fires when the pointer is pressed down on the target. |
| **Pointer Up** | Fires when the pointer is released over the target. |
| **Pointer Drag** | Fires repeatedly as the pointer moves after being pressed down on the target, until the pointer is released. |
| **Click** | Fires when the target is clicked or tapped. |
| [Focus](#focus) | Fires when the target receives focus. |
| [Blur](#focus) | Fires when the target loses focus. |
| [Keyboard](#keyboard) | Fires when a key is pressed or released while the target has focus. |
| [Gamepad](#gamepad) | Fires on gamepad input, such as a button press or stick movement. |
| [Text Input](#text-input) | Fires when text is entered while the target has focus. |
| [Semantic Action](#semantic-action) | Fires when an assistive technology, such as a screen reader, performs an action on the target, like a tap, increase, or decrease. |
### View Model Change
This **Listen to** option is only available when the listener target is an artboard or nested component.
View Model Change listeners fire whenever the selected property changes. You can’t specify an expected value or direction of change. For example, a Boolean listener fires when the value changes from true to false or from false to true.
If the property can be reached from more than one place, use **Source** to choose the path to it.
### Rive Event
This **Listen to** option is only available when the listener target is an artboard or nested component.
We strongly recommend using [Data Binding](/docs/editor/data-binding/overview) to communicate between artboards instead of relying on nested Rive events.
### Pointer Exit
**Pointer Exit** only fires while Rive can read the pointer position. If the target touches the edge of the canvas or container, moving the pointer out of the container may not trigger **Pointer Exit** because the pointer has left the area Rive is tracking.
### Mouse buttons
**Pointer Down**, **Pointer Up**, **Click**, and **Pointer Drag** listeners have a second dropdown to choose which mouse button triggers them: **Primary Button**, **Secondary Button**, or **Middle Button**. Use **Secondary Button** for right-click interactions, such as custom context menus.
When a state machine is playing in the editor, right-click still pans the canvas and opens menus, except over a listener set to **Secondary Button**.
> [!WARNING]
>
> Runtimes that don't support this feature ignore **Secondary Button** and **Middle Button** listeners. They don't fire them on a left click instead.
### Focus
Turn on **Focusable** for an element to add it to the focus order. Use **Focus** listeners to react when the element gains focus and **Blur** listeners to react when it loses focus.
The **Focus Target** action moves focus to a specific element, and **Focus Traversal** steps through the focus order. See [Focus](/docs/editor/accessibility/focus) for focus order, scopes, and more.
### Keyboard
To react to keys, add a **Keyboard** listener and choose **On Key Down**, **On Key Repeat**, or **On Key Up**. Keys go to the element that has focus.
To choose which keys trigger the listener, click **+** next to **Keys** in the Inspector. Each key has:
* **Key code**: Click the field, then press the key. Any modifier keys you hold, such as Shift or Ctrl , are saved with it. Press Esc to cancel.
* **Phase**: Which key events trigger the listener: **On Key Down**, **On Key Repeat**, and **On Key Up**. Turn on any combination.
To try keyboard input in the editor, press **Option+Space** to play with keyboard capture on, or click **Toggle Keyboard Capture** in the playback header. This lets keys reach your file instead of triggering editor shortcuts.
### Gamepad
Add a **Gamepad** listener to drive a state machine from a controller's buttons and sticks. Scripts can listen to gamepad events too.
The gamepad icon at the bottom of an open file turns green when Rive can see your controller.
To choose what triggers the listener, click **+** next to **Inputs** in the Inspector. With no inputs, the listener reacts to every gamepad event. Each input has:
* **Kind**: What to listen for. **Button** is a button press or release, **Axis** is a stick or trigger moving, and **Connected** and **Disconnected** fire when a gamepad connects or disconnects.
* **Mapping**: How the button or axis is picked. **Standard** picks it by name in the standard gamepad layout. **Index** picks it by the raw number the controller reports, whatever its layout.
* **Button** or **Axis**: The button or the stick or trigger axis to listen to.
* **Phase**: For buttons, whether the listener fires **On Press**, **On Release**, or both.
### Text Input
Pick the **Text Input** tool in the toolbar and draw an editable text field. Draw it over a layout to add it to that layout.
Use the **Text Input** section of the Inspector to set the field's font, colors, placeholder, selection color, background, and single line or multiline mode. Add a **Text Input** listener to react when text is entered while the field has focus. See [Text Input](/docs/editor/text/text-input) for details.
### Semantic Action
The **Semantic** section of the Inspector gives an element a role, such as button, checkbox, slider, or text, plus its traits and state. This helps screen readers read and navigate your file.
Use **Semantic Tap**, **Semantic Increase**, and **Semantic Decrease** listeners to respond to screen reader actions. See [Semantics](/docs/editor/accessibility/semantics#actions) for details on configuring semantic actions.
## Phase
**Phase** controls when a listener runs compared to the elements inside its target.
* **Normal:** The listener runs in the usual order, after the elements inside its target have had a chance to handle the input.
* **Capture:** The listener runs before anything inside its target, including a component's own listeners and built-in behavior like typing in a [Text Input](/docs/editor/text/text-input).
A capture listener for a specific key and modifiers takes that key, so nothing inside the target receives it. A capture listener for a pointer press takes the whole press, until the pointer is released.
Use **Capture** to override keys or clicks on a component you can't edit.
## Listener actions
When a listener fires, it runs its [actions](/docs/editor/state-machine/actions), such as setting a view model property, moving an object to the pointer, or reporting an event. To add one, select the listener and click **+** in the panel below the graph. You can add as many actions as you need.
When you create a listener with **+** in the **Animations** panel, you choose its first action:
* **View Model Change**: Changes a view model property.
* **Input Change**: Changes a legacy input. Deprecated; use **View Model Change** instead.
* **Align Target**: Moves an object to the pointer.
* **Report Event**: Fires a Rive event.
* **Scripted Action**: Runs a [listener action script](/docs/scripting/protocols/listener-action-scripts).
* **Focus**: Moves keyboard focus.
See [Action types](/docs/editor/state-machine/actions#action-types) for details.
# State Machine Overview
Source: https://rive.app/docs/editor/state-machine/state-machine
Connect timelines with logic to build interactive graphics, and run several at once with layers.
A state machine connects your [timelines](/docs/editor/animate-mode/timeline) with logic. It decides which animation plays, when it changes, and how it blends into the next one, based on data, user interaction, or time. This is what makes a Rive graphic interactive, and it's what your app or game controls at runtime.
For example, a button might have Idle, Hover, and Pressed timelines. A state machine plays Idle by default, switches to Hover when the pointer moves over the button, and to Pressed when it's clicked.
[YouTube video player](https://www.youtube.com/embed/0Hb7SlEW6MI)
## How a state machine works
A state machine is made of:
* **[States](/docs/editor/state-machine/states)**: what's playing, usually a timeline or a blend of timelines.
* **[Transitions](/docs/editor/state-machine/transitions)**: the connections between states, with conditions that decide when the state machine moves from one state to another.
* **[Layers](#layers)**: each layer is its own graph of states and transitions. Layers play at the same time.
The state machine is driven by:
* **[Data binding](/docs/editor/data-binding/overview)**: transition conditions can check view model properties, so your app can change a value and the state machine responds.
* **[Listeners](/docs/editor/state-machine/listeners)**: respond to pointer, keyboard, and other interactions on the artboard.
* **Time**: a transition can wait until a timeline finishes, or reaches a set point, with [Exit Time](/docs/editor/state-machine/transitions#exit-time).
> [!NOTE]
>
> Older files use [Inputs](/docs/editor/state-machine/inputs) to drive state machines. Use data binding for new work.
## Creating a state machine
Every artboard starts with one state machine, and you can add as many as you need. Your app chooses which state machine to play at runtime.
**Step 1**
In the **Animations** list, click **+** and select **State Machine**.
**Step 2**
Select the state machine to open its graph in place of the timeline.
The graph is where you add states and connect them with transitions. A new state machine's graph has the Entry, Any State, and Exit states. See [Default states](/docs/editor/state-machine/states#default-states).

To preview the state machine, click the play button above the graph. It runs on the stage the same way it will at runtime, so you can click, hover, and change bound values to test it.
### Playback header
While a state machine plays, a blue frame surrounds the stage it plays in. The header at the top of the frame shows the state machine's name and two buttons:
* **Stop Playback**: Stops the state machine.
* **Toggle Keyboard Capture**: Sends key presses to the state machine instead of the editor's shortcuts, so you can test [Keyboard listeners](/docs/editor/state-machine/listeners#keyboard). Press **Option+Space** to stop playback while keys are captured.
Click another stage split to move the frame there.
## Graph controls
The buttons above the graph help you navigate and debug it:
* **Zoom**: Shows the graph's current zoom. Click it to type an exact value, zoom in or out, **Zoom to Fit**, or **Zoom to 100%**. Turn on **Snapping** to snap states to the grid while you drag them.
* **Console**: Logs what the state machine does while it plays, including frames, layer and state changes, transitions, input changes, and fired events. The log clears each time playback starts.
## Layers
A layer plays one state at a time. To play more than one animation at once, add more layers. For example, one layer can play a character's idle and walk cycle while another layer plays its blinking.
[YouTube video player](https://www.youtube.com/embed/7Vb1LosMzwk)
### Adding a layer
Click **+** in the **Layers** tab.

### Layer order
When two layers animate the same property, the layer lower in the list wins. If your layers animate different properties, their order doesn't matter.
To change the order, drag layers up or down in the **Layers** tab.

[YouTube video player](https://www.youtube.com/embed/Fc9MutscvAo)
### Layer options
Click the **...** button next to a layer to open its options.

* **Delete**: Deletes the layer.
* **Duplicate**: Creates a copy of the layer, with its states and transitions.
* **Disable**: Stops the layer from playing without deleting it. Useful for testing one layer at a time. A disabled layer shows a hidden icon in the **Layers** tab; click it to enable the layer again.
* **Snapping**: Turns snapping on or off for states and transitions in the layer's graph.
# States
Source: https://rive.app/docs/editor/state-machine/states
Add states to a state machine to play timelines, blend them together, and mark where each layer starts and stops.
A state is what a [state machine](/docs/editor/state-machine/state-machine) layer is doing at a given moment. Most states play a [timeline](/docs/editor/animate-mode/timeline), or blend several timelines together. [Transitions](/docs/editor/state-machine/transitions) move the layer from one state to the next.
Every layer has three default states, Entry, Any State, and Exit, and you add the rest:
* **Single** plays one timeline.
* **1D** blends timelines based on one value.
* **Additive** layers several timelines on top of each other, each with its own amount.
## Default states
Every layer starts with an Entry State, an Any State, and an Exit State.

### Entry State
The Entry State is where the layer starts. When the state machine starts, the layer follows the transition out of the Entry State to its first state.
You can connect the Entry State to more than one state, and use [conditions](/docs/editor/state-machine/transitions#transition-conditions) to choose which one the layer starts in. For example, a switch can start in its On or Off state depending on a bound value.

### Any State
Transitions out of the Any State can happen from whatever state the layer is in. Use it for states you need to reach from anywhere, such as changing a character's outfit or setting a rating, without drawing a transition from every other state.
[YouTube video player](https://www.youtube.com/embed/P6Z3oeAJWqY)

### Exit State
[YouTube video player](https://www.youtube.com/embed/JuJwak2ikJ4)
Transitioning to the Exit State stops the layer. It doesn't just stop the current animation: the layer stops advancing entirely, and its objects stay where the last animation left them. Other layers keep playing.
You'll rarely need it, but it's useful for a layer that has finished its work, such as an intro that plays once. Stopping the layer saves the work of running it.
For example, to play a timeline once and then stop its layer:
**Step 1**
Put the timeline on its own layer, connected from the Entry State.
**Step 2**
Add a transition from the timeline's state to the Exit State.
**Step 3**
Set the transition's [Exit Time](/docs/editor/state-machine/transitions#exit-time) to 100%, so it happens once the timeline has played all the way through.
A layer that has exited can still start again through a transition from the Any State.
## Adding a state
* **From a timeline:** Drag a timeline from the **Animations** list onto the graph. This creates a Single state that plays it.
* **Empty:** Right-click the graph and choose the type of state to add. Then pick its timelines in the Inspector.

To change a state's type later, select it and change **Type** in the Inspector.
To line up states in the graph, select two or more and use the align and distribute buttons at the top of the Inspector.
## Single states
[YouTube video player](https://www.youtube.com/embed/bGW1tNpNt-Y)
A Single state plays one timeline. Most of a state machine is usually made of Single states. The timeline plays the way it's set up, as a one-shot, a loop, or a ping-pong. See [Animation type](/docs/editor/animate-mode/timeline#animation-type).
Select a Single state to change its options in the Inspector:
* **Timeline**: The timeline the state plays. Type in the dropdown to search for a timeline.
* **Speed**: How fast the timeline plays. `1x` is normal speed, `2x` is twice as fast, and negative values play it backward.
## Blend states
A blend state plays multiple timelines at once and mixes them together. Use blend states for anything driven by a changing value, such as a health bar, a loading bar, a scroll position, or a face rig.
Blends work best with timelines that key only the properties they need. For example, each timeline in a health bar might key only the bar's X scale.
### 1D blend
A 1D blend mixes its timelines based on a single number. Each timeline is set at a value, and as the number moves between two timelines' values, the blend crossfades between them.
For example, a health bar can blend between an Empty timeline at `0` and a Full timeline at `100`, driven by a health property.

**Step 1**
Add a state, and set its **Type** to **1D**.
**Step 2**
In **Input**, choose the number that drives the blend. Usually this is a [view model](/docs/editor/data-binding/overview) property, but legacy number [inputs](/docs/editor/state-machine/inputs) are listed too.
**Step 3**
In **Timelines**, click **+** to add each timeline, and set the value where it plays at full strength.
The graph above the timelines shows how they mix across the range. While the state machine is playing, a marker moves across it to show the current value.
#### Capture Base State
**Capture Base State** is the toggle next to the blend's property, and it's on for new 1D blends. When it's on, the blend starts each frame from the original values of the properties its timelines key, then mixes the timelines on top. This keeps the result the same for any given value.
When it's off, the blend mixes on top of whatever values were already there, so the result can depend on what played before.
### Additive blend
An Additive blend plays several timelines on top of each other, each with its own amount from 0 to 100. Use it to combine independent motions, such as mixing smile, frown, and surprise poses on a face.

In **Timelines**, click **+** and choose how the new timeline's amount is set:
* **Mix by value**: A fixed amount that you set in the Inspector. Use it for a base pose that's always applied.
* **Mix by view model**: The amount comes from a [view model](/docs/editor/data-binding/overview) property, so your app can change it.
* **Mix by input**: The amount comes from a legacy [input](/docs/editor/state-machine/inputs).
## State options
Select a state to see its options in the Inspector:
* **Name**: The state's name.
* **Caption**: A note for collaborators or your future self. See [Captions](#captions).
* **Type**: Single, 1D, or Additive.
* **Transitions**: The [transitions](/docs/editor/state-machine/transitions) leaving the state. Click the eye icon to disable one, or **-** to remove it.
* **Randomize Exit**: Picks one of the state's transitions at random, weighted by a **Factor** you set on each one. See [Randomize exit](/docs/editor/state-machine/transitions#randomize-exit).
Single states also have **Timeline** and **Speed**, and blend states have their blend settings.
### Captions
When a state has a caption, an info icon appears on it in the graph. Hover over the icon to read the caption. Use captions to explain why a state exists or how complex logic works.
Captions are only visible in the editor, and aren't exported.
## Actions
A state can run [actions](/docs/editor/state-machine/actions) when it starts or ends, such as setting a view model property, reporting an event, or moving focus. Select the state, then click **+** next to its name in the panel below the graph.
## Common issues
[YouTube video player](https://www.youtube.com/embed/TnTvFkMC7iI)
## Example: a simple button
This video builds a button with two layers of interactivity, hover and click.
[YouTube video player](https://www.youtube.com/embed/hlEPcxhc2pI)
# Transitions
Source: https://rive.app/docs/editor/state-machine/transitions
Transitions define how and when a State Machine moves from one state to another. A transition is made up of four parts:
> [card] Path
>
> The direction the transition travels.
>
> **Example**: A character might have one path from **Idle** to **Walk**, and another from **Walk** back to **Idle**.
> [card] Conditions
>
> When the transition occurs.
>
> **Example**: A character might transition to **Walk** when a button is pressed, then back to **Idle** when the button is released.
> [card] Properties
>
> How the transition behaves.
>
> **Example**: You might set the transition duration to `0.2` seconds so the change between states feels smoother.
> [card] Actions
>
> Extra behavior to perform when the transition occurs.
>
> **Example**: A transition might fire an event, set a property value, or align a target.
[YouTube video player](https://www.youtube.com/embed/C4KNgrrqt7k)
## Transition path
A transition path determines how the State Machine moves from one state to another.
To create a transition path, move your cursor near the state you want to leave until the circle appears. Click and drag from the circle to the state you want to transition to.

Once you connect two states, the transition path shows a circle with an arrow icon indicating the transition direction. In this example, the State Machine can move from Timeline 1 to Timeline 2, but not from Timeline 2 back to Timeline 1.
To allow the State Machine to move back to Timeline 1, create another transition path starting from Timeline 2.

You can create multiple transitions between the same two states. Each transition can have different [conditions](#transition-conditions), allowing you to create “or” logic.

## Transition Conditions
Conditions determine when a transition can occur.
> [!NOTE]
>
> Without conditions, transitions fire as soon as they are reached. This can cause a State Machine to rapidly move between states or skip directly to a single animation.
[YouTube video player](https://www.youtube.com/embed/30HJo_DaLDk)
### Adding a condition
To add a condition to a transition, select the transition, then click the plus button next to **Conditions**.
A condition has three parts:
* **Source value** - the value or event the condition watches
* **Operator** - how the source value is compared
* **Comparison value** - the value the source value is compared against
For example, a character might transition from **Idle** to **Walk** when `isWalking` is `true`.
In this condition, `isWalking` is the **source value**, **equals** is the **operator**, and `true` is the **comparison value**.

#### The source value
Conditions can be driven by many different sources, including:
* View Model properties
* Events
* Built-in properties such as artboard width, height, and ratio
* Object properties: choose **Component**, then pick the object and which of its properties to compare

#### The operator
Conditions can use comparisons such as equals, does not equal, greater than, greater than or equal to, less than, and less than or equal to. The available comparisons depend on the type of value being compared.

#### Comparison value
The comparison value is the value the source value is compared against.

You can enter a fixed comparison value, such as `true`, `100`, or `"mobile"`. You can also data bind the comparison value to another property, allowing the transition to compare against dynamic data.
For example, a transition might occur when `speed` is greater than a data-bound `walkThreshold` value.
### Adding multiple conditions
You can add multiple conditions to a single transition. All conditions must be met before the transition occurs. The first condition starts with **if**, and each one after it starts with **and**.

### Editing multiple transitions
When you select several transitions, the conditions panel can show them as groups. Transitions with identical conditions share one group, so editing a condition in the group changes it on all of them. Transitions whose conditions differ get a group of their own.
Use the **Group Transitions** button in the conditions panel, next to the transition options, to turn grouping on or off. Grouping is on by default, and the button only appears when some of the selected transitions can be grouped. Transitions with a [scripted condition](/docs/scripting/protocols/transition-condition-scripts) are never grouped.
## Transition properties
Once you’ve added a transition, selecting the direction indicator will allow you to configure the transition. There are three different sections to the transition panel, the transition properties, conditions, and interpolation.
> [!NOTE]
>
> Selecting multiple transitions allows you to update multiple properties at once.

### Duration
The duration property describes how long it takes for a transition to occur.
The duration is set to zero by default, meaning the transition happens immediately. So, when we transition between these two animations, it appears as though the object snaps from one side of the artboard to the other.
> [card] [Learn by remixing](https://rive.app/community/files/28136-transitions-demos?utm_source=docs\&utm_medium=docs_link_card\&utm_campaign=docs_to_marketplace_links)
>
> Open this file on Marketplace, then click Remix to experiment in the Rive Editor.
### Exit Time
Exit Time tells the state machine how much of the state must play before transitioning.
By default, Exit Time is unchecked. To enable Exit Time, use the checkbox. Once the setting is enabled, you can use either a time value or percent.
For example, if you want the state machine to play the entire animation before transitioning, you can either enter the duration of the animation, or use 100%.

When the transition leaves a blend state, use **Exit Source** to choose which of the blend's timelines Exit Time is measured against. This option only shows when a single transition is selected.
### Pause source when exiting
**Pause Source When Exiting** pauses the animation in the state you are leaving while the transition plays.
In this example, the up-and-down motion pauses as soon as the transition begins.

### Allow exit during transition
**Allow exit during transition** controls whether the State Machine can leave a transition before that transition finishes.
For example, if a button is transitioning from **Idle** to **Hover** and the user moves their cursor away, **Allow exit during transition** lets it transition back to Idle immediately.

### Interpolation
You can add interpolation to your transition at the bottom of the Transitions Panel. By default, the interpolation is set to linear, but you can use the cubic and other interpolations.
If you are unfamiliar with the basics of Interpolation, see [Interpolation (Easing)](/docs/editor/animate-mode/interpolation-easing).
## Actions
A transition can run [actions](/docs/editor/state-machine/actions) when it starts or finishes, such as setting a view model property, reporting an event, or moving focus. Unlike conditions, which decide whether a transition happens, actions do something when it does. Select the transition, then click **+** next to its name in the panel below the graph.
## Randomize exit
**Randomize Exit** lets a state choose from its outgoing transition paths at random.
To use it, select the origin state and enable **Randomize Exit**. The state lists each path leaving it and lets you assign a weight to each path.
The higher the weight, the more likely that path is to be chosen. For example, if **Timeline 1** has a weight of `3` and **Timeline 2** has a weight of `1`, the State Machine has a 75% chance of transitioning to **Timeline 1** and a 25% chance of transitioning to **Timeline 2**.
You can also set a path's weight by selecting its transition and changing **Randomization Factor** in the Inspector.
## Disabling a transition
You can temporarily disable a transition without deleting it. Disabling is useful when you want to isolate part of a state machine for testing, or temporarily remove a path without losing its configuration.
There are two ways to toggle a transition's enabled state:
* **From the transition panel:** select the transition and click the enable/disable icon in the panel.
* **From the canvas:** right-click the transition and choose **Disable transition** (or **Enable transition** if it's already disabled).

# Tagging
Source: https://rive.app/docs/editor/tagging
Organize objects, data, assets, and animations with color-coded tags, then filter, lock, or select by tag.
Tags help you organize a file. Create a tag, assign it to items such as bones, groups, View Models, assets, or animations, then use it to filter a panel, lock objects on the stage, or select everything that shares the tag.
Tags belong to the file, not to a single artboard. Any tag you create is available on every artboard and in every panel that supports tags: the [Hierarchy](/docs/editor/interface-overview/hierarchy), Data, Assets, and Animations panels.
> [!NOTE]
>
> Tags are available on paid plans. [Learn more about our plans and pricing](https://rive.app/pricing?utm_source=docs\&utm_medium=content).
## Creating tags
You can create a tag from the [Inspector](/docs/editor/interface-overview/inspector), from a panel's tags menu, or while assigning it to an item.
### From the Inspector
**Step 1**
Click an empty area of the stage so nothing is selected.
**Step 2**
In the **Tags** section of the Inspector, click **+**.
**Step 3**
Enter a name for the tag, then click the color swatch to choose its color.
You can come back here at any time to rename a tag, change its color, or drag tags to reorder them. To delete a tag, right-click it and remove it.
### From the tags menu
Open the context menu in the header of the Hierarchy, Data, Assets, or Animations panel, then select **Create Tag**. The new tag appears in the Inspector, where you can rename it and set its color.
### While assigning a tag
**Step 1**
Select one or more items on the stage or in a panel.
**Step 2**
Right-click the selection and open **Add Tag**.
**Step 3**
Select an existing tag, or select **New Tag** to create one and assign it in a single step.
To remove a tag from an item, right-click it and select the tag under **Remove Tag**.
## Using the tags menu
Each panel that supports tags has a **Tags** section in its header context menu. It includes these options:
* **Create Tag** adds a new tag to the file.
* **Edit Tags** clears the selection so you can edit tags in the Inspector.
* **Collapse Tags** / **Reveal Tags** hides or shows tag names next to tagged items.
* A submenu for each tag with **Filter**, **Lock**, and **Select**.

### Collapsing tags
Tagged items show the tag's color and name to the right of the item.
Select **Collapse Tags** to hide the names and show only the colors. Select **Reveal Tags** to show the names again. This setting applies to the whole file.
### Filtering by tag
Open a tag's submenu and check **Filter** to show only the items that have that tag. Active filters appear next to the panel name.
You can filter by as many tags as you want. An item stays visible if it has any of the filtered tags. Each panel has its own filters, so filtering the Hierarchy doesn't affect the Data, Assets, or Animations panels.
To clear every filter in a panel, select **Remove filters** from the tags menu.
> [!TIP]
>
> Filter by tag to show only the controls you need while animating, such as the bones and targets of a character rig.
### Locking by tag
Open a tag's submenu in the Hierarchy and check **Lock** to lock every object with that tag. You can't select a locked object on the stage. You can also lock or unlock a tag with the lock icon next to it in the Inspector.
Locking is only available in the Hierarchy. Use it when you hand off a file to another animator, so they don't move objects that shouldn't change.
### Selecting by tag
Open a tag's submenu and select **Select** to select every item in that panel with the tag. In the Inspector, click the target icon next to a tag to select every tagged object on the stage.
# Font Assets
Source: https://rive.app/docs/editor/text/fonts
Import and customize fonts.
## Importing fonts
See [Importing Assets](/docs/editor/fundamentals/assets-overview#importing-assets) for information about importing files, including TTF and OTF files.
### Google Fonts
You can add Google Fonts directly from the text style font options. Select a text run, choose a Google Font, and Rive adds the font to the Assets panel automatically.
## Export options
Font assets include an Include option that controls which glyphs are included when the font is exported.
* **All glyphs**: Include the full font.
* **Glyphs used**: Include only the glyphs used in the file.
* **Custom**: Include a custom set of glyphs.

> [!NOTE]
>
> Fonts can significantly increase the size of your exported `.riv` file, especially when exporting **All glyphs**. Use **Glyphs used** or **Custom** when you only need a smaller set of characters.
> [!TIP]
>
> To control which glyphs are included, create an artboard that you do not export to the `.riv` file. Add a text run with the exact characters you want to include, then set the font asset’s **Include** option to **Glyphs used**.
>
> For example, if your file only needs numbers, add a text run with `0123456789`. Those glyphs will be included in the exported font.
>
> 
### Custom - Export Scripts
When **Include** is set to **Custom**, you can use **Export Scripts** to choose which glyph groups to include, such as Latin, Thai, or other writing systems.

# Text Input
Source: https://rive.app/docs/editor/text/text-input
Add editable text fields that users can type into at runtime.
A text input is an editable text field, like a search bar, login form, or chat box. Users can click or tab into it, type, select text, and paste, without you building any of that behavior yourself.Each text input is a [Stateful Component](/docs/editor/data-binding/stateful-components) built from Rive's bundled Text Input library. Its appearance and value are view model properties. This means you can key them in [animate mode](/docs/editor/fundamentals/design-vs-animate-mode), bind them with [Data Binding](/docs/editor/data-binding/overview), and react to typing with [listeners](/docs/editor/state-machine/listeners#text-input).Tip**Example - Personalized greeting**Let's say you're building a sign-up card that greets the user by name. Add a text input for the name and bind its **Value** to a `name` string property on your view model. Then bind a [Text Run](/docs/editor/text/text-runs) in the greeting to the same property. As the user types, the greeting updates, and your app can read `name` from the view model at runtime.## Creating a text input**Step 1**Open the text tools menu in the toolbar and select **Text Input**.**Step 2**Click the artboard to create a single-line input, or drag to create a multiline input at the size you drew.A click creates a 200 × 40 single-line field with its text centered vertically. A drag creates a multiline field with its text aligned to the top and extra top and bottom padding.Draw over an existing [Layout](/docs/editor/layouts/layouts-overview) to add the input to that layout. Draw over the bare artboard to place the input at that spot, inside its own absolutely positioned layout.To try the input, switch to [animate mode](/docs/editor/fundamentals/design-vs-animate-mode), select a state machine, and play it. Click the field to focus it, then type. Click anywhere outside the field, including the empty space around the artboard, to remove focus. This works the same way in the editor and at runtime.> [!TIP]
>
> Press `Esc` while placing an input to cancel it.## Configuring a text inputSelect a text input to edit its properties in the **Text Input** section of the Inspector.### AlignmentUse the alignment toggles at the top of the section to set the horizontal and vertical alignment of the text inside the field.### Value- **Value:** The text in the field. Set it to give the field a starting value, or bind it to read and write the text at runtime.
- **Font:** The font, size, and weight.
- **Text color:** The color of the typed text.
- **Multiline:** Allows the text to wrap onto multiple lines and the user to enter line breaks. Turn it off for single-line fields like search bars.
- **Obscure:** Masks the text as bullets. Use it for password fields.### Limits- **Max Characters:** The most characters the field accepts.
- **Max Lines:** The most lines the field accepts. Lines are counted as they wrap on screen, not by line breaks.Set either to `0` for no limit. You can set them in the Inspector or bind them. The bundled Text Input component also exposes both as view model properties.Once the field reaches a limit, typing and `Enter` stop adding text, and a paste keeps only the part that fits. The limits only apply to what the user enters. Text set through a data binding is never trimmed.### Placeholder- **Placeholder:** Text shown when the field is empty, such as "Search" or "Email address."
- **Placeholder color:** The color of the placeholder text.### Selection- **Cursor color:** The color of the text cursor.
- **Selection color:** The highlight color behind selected text.
- **Selection radius:** The corner radius of the selection highlight.### Container- **Background color:** The fill color of the field.
- **Stroke color:** The border color and width.
- **Padding:** Space between the border and the text. Set horizontal and vertical padding, or switch to individual edges to set **Left**, **Right**, **Top**, and **Bottom** padding separately.
- **Corner radius:** Rounds the corners of the field. Corners are linked by default; unlink them to set each corner separately.### FocusClick **Focus** at the bottom of the section to fire the input's focus trigger. While the state machine plays, this focuses the field. Bind the trigger to focus the field from your own logic, such as when a form opens.> [!NOTE]
>
> Every property in the section can be keyed and bound like any other view model property. Hover a property and click the bind button to [bind it](/docs/editor/data-binding/binding-data).## Responding to text inputAdd a listener to react when the user interacts with a text input:- **Text Input:** Fires when text is entered while the field has focus.
- **Focus** and **Blur:** Fire when the field gains or loses focus. Use them to animate a focus ring or show a hint.See [Listeners](/docs/editor/state-machine/listeners) for setting up listeners and their actions. In scripts, use [`ListenerContext`](/docs/scripting/api-reference/artboards/listener-context) to check for a text input event and read its [`TextInput`](/docs/scripting/api-reference/artboards/text-input) data.> [!TIP]
>
> To read the field's text in your app, bind **Value** to a string property on your view model rather than handling each keystroke.## Custom text input componentsYou can make your own component show up in the editor as a text input. Select the component and set **Type** to **Text Input** in the Inspector. **Type** only appears on components.Instances of a **Text Input** component use the **Text Input** section in the Inspector instead of the usual component properties. The section lists the properties the component exposes on its [view model](/docs/editor/data-binding/stateful-components). To get the same rows as the bundled component, use the same property names, such as `text`, `placeholderText`, `textColor`, and `focus`.Set **Type** back to **Regular** to treat it as a standard component.## Runtime supportText input needs keyboard and text input from the host app, so it's only available in runtimes that pass that input to Rive.
\> \[accordion]
\>
\> \ \\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
See [Feature Support](/docs/feature-support) for the full list of features by runtime.
# Text Modifiers
Source: https://rive.app/docs/editor/text/text-modifiers
Text Modifiers let you animate or transform individual characters, words, lines, or glyphs within a text object.
By combining ranges, falloff, and animated offsets, you can create effects such as text reveals, wave animations, bouncing characters, and per-letter motion.
[YouTube video player](https://www.youtube.com/embed/RkahZjwf3aQ)
## Modifier Group
A Text Modifier Group combines a **Range** and a set of **Properties**.
* **Properties** determine what changes, such as position, rotation, scale, opacity, or follow path.
* The **Range** determines which characters, words, or lines are affected.
A single modifier group can affect multiple properties that share the same range.
Multiple modifier groups can be combined to create layered effects. For example, one modifier group might animate character scale while another animates position.
### Adding a Modifier Group
Select a text object, then click the `+` button in the **Text Modifier** panel.

### Properties
Properties determine how the text is modified.
Each modifier group can modify one or more of the following properties:
* **Position** - Move text along the X and Y axes.
* **Rotation** - Rotate text around its origin.
* **Scale** - Change the size of the text.
* **Origin** - Adjust the pivot point used for rotation and scale.
* **[Opacity](#opacity)** - Change the transparency of the text.
* **[Follow Path](#follow-path)** - Align text to a path and control how glyphs follow its direction.
* **Variables** - Adjust variable font axes such as weight or width. Requires a variable font that supports the selected axis.
Multiple properties can be combined within a single modifier group to create more complex effects.
#### Adding a property
Select a text object, then click the `+` button in the **Modifier Group**. Each property has its own settings, which can be adjusted and animated.

> [!TIP]
>
> If text modifier range or values aren't visible on the stage, open the **View Options** menu and make sure **Text Modifier Range** **Text Modifier Values** are enabled.
>
> 
#### Opacity
The Opacity value controls the opacity of text within the modifier group's range.
The Invert option controls the opacity of text outside the range:
* Disabled: Text outside the range is fully transparent (0% opacity).
* Enabled: Text outside the range is fully visible (100% opacity).

#### Follow Path
> [!NOTE]
>
> To make non-text objects follow a path, use the [Follow Path Constraint](/docs/editor/constraints/follow-path-constraint) instead.
The Follow Path modifier allows text to follow the shape of a vector path. This can be used to create curved text, circular text layouts, or animated text that moves along a path.
* **Follow** - The path to follow.
* **Trim Start and End** - Defines where text begins and stops following the path. Text outside the trimmed section continues from the nearest trim point in the direction the path is facing.
* **Offset** - Where along the path to start.
* **Strength** - Controls how strongly the text follows the path. At 0%, text stays in its original position. At 100%, text follows the path completely. Animate Strength to transition text onto or off of a path.
* **Auto Orient Glyphs** - Make the rotation of the glyph follow the path.
* **Auto Orient Lines** - Rotates each line to follow the direction of the path.
### Range
The range can be defined as a percentage of the text length or as an index value.
Ranges can be applied by character, word, or line. Open the Range Options fly-out to configure the range behavior.
Tip
**Example**
A range with a start value of 0% and an end value of 50% affects only the first half of the text. If the modifier group applies a scale of 25%, only glyphs within the first half of the text will be scaled.
You can see a visual representation of the range via a shaded area on the stage. You can configure the stage visual options in the visibility menu on the toolbar.

Multiple ranges can be added to a single modifier group to create complex effects.
#### Run
Determines whether the modifier is applied to the entire text object or only to a specific text run.
When a text object contains multiple text runs, modifiers can be limited to a single run instead of affecting all text.
#### Falloff
Use the falloff values to add interpolation to the applied modifier properties. For example, a modifier group that scales glyphs to 200% with a range from 0% to 100% and a falloff of 25% to 75% will gradually scale glyphs up from 100% to 200% over the first quarter of the text, and back down again over the last quarter of the text.
The falloff can be visualized via the darker shading on the stage guide.

#### Offset
Use Offset to move the range along the text. Try animating the offset value to create wipe effects along a text value. For example, a scale modifier can animate the offset to make individual glyphs scale up and back down again.

#### Range options
Additional range options can be found in the fly-out alongside the range name for more fine-grained control over the range selection behavior.
**Increment**
Define whether modifier properties get applied by:
* Characters (with or without spaces)
* Words
* Lines
With **Characters** selected, turn on **Exclude Spaces** to skip spaces when counting characters.
> [!NOTE]
>
> The increment value will affect an index-based Range Type.
**Mode**
Defines how modifier values are combined when multiple ranges overlap.
For example, if two overlapping ranges each apply a scale of 200%, an **Add** mode would combine them to produce a scale of 400%.
**Clamp**
The checkbox next to **Mode** keeps the combined amount between 0% and 100% after this range is applied. Turn it on so overlapping ranges can't push the modifier past its full effect, or below zero with **Subtract**.
> [!NOTE]
>
> Turn on Modifier Range Values in the visibility menu to get a numerical indication of how much a Text Modifier is affecting glyphs.
**Strength**
Adjust the overall influence of the modifier within the range. A value of 0% disables the modifier, while 100% applies its full effect.
**Range Type**
Set the range type to configure range start, end, and offset values as a percentage of the text length, or by indices. You may also want to consider which increment value to use alongside the Range Type. For example, an index value of 1 incremented by characters will target the second character, whereas an index value of 1 incremented by words will target the start of the second word.
**Falloff Interpolation**
Modify the falloff interpolation to define a custom cubic curve. The falloff defaults to linear interpolation.
## View options
Toggle visual guides on the stage via the visibility menu in the toolbar:
* Text Modifier Range: Toggle the display of a shaded area on the stage to highlight the range position on a selected text object.
* Text Modifier Range Values: Toggle the display of per-glyph values on modifier ranges to indicate the applied strength of a given modifier.

## Use case: animating a text pendulum
This simple example will get you used to animating with Text Modifiers.
[YouTube video player](https://www.youtube.com/embed/Wec_F45NLoY)
# Text
Source: https://rive.app/docs/editor/text/text-overview
Create and format text, control sizing, wrapping, and overflow, and convert text to shapes.
Rive text is live text, not a picture of text. It's laid out at runtime, so you can change its content while your graphic runs, animate it, and fit it to any size of container. Use it for labels, buttons, counters, captions, and anything else that needs to change or be translated.
A text object is built from a few parts:
* **[Text runs](/docs/editor/text/text-runs)**: The content. A text object has one or more runs, each with its own style. [Bind a run to a string property](/docs/editor/data-binding/overview) to change its content at runtime.
* **[Text styles](/docs/editor/text/text-styles)**: The font, size, spacing, and paint of each run.
* **[Fonts](/docs/editor/text/fonts)**: The typefaces your styles use, and how much of each font is exported.
* **[Text modifiers](/docs/editor/text/text-modifiers)**: Animate or transform individual glyphs, words, or lines, or make text follow a path.
* **[Text input](/docs/editor/text/text-input)**: An editable field that users can type into at runtime.
This page covers creating text and the options on the text object itself: sizing, wrapping, alignment, and overflow.
[YouTube video player](https://www.youtube.com/embed/nykDEo6XqXY)
## Creating text
**Step 1**
Press `T`, or select the **Text Tool** in the toolbar.
**Step 2**
Add the text to the artboard:
* **Click** to create text that sizes itself to fit its content (**Auto Width**).
* **Click and drag** to draw a text box of a set size (**Fixed Size**).
**Step 3**
Type your text.
To edit text later, double-click it.
## Sizing
Sizing controls how the text's bounds respond to its content.
* **Auto Width**: The width and height grow and shrink to fit the text.
* **Auto Height**: The width stays fixed, and the height grows to fit the text.
* **Fixed Size**: The width and height stay fixed. Use [Overflow](#overflow) to decide what happens when the text doesn't fit.

## Alignment
Horizontal alignment (left, center, right) and vertical alignment (top, middle, bottom) position the text inside its bounds.

> [!NOTE]
>
> Alignment only has an effect where the bounds are larger than the text. With **Auto Width**, the bounds always fit the text, so neither alignment changes anything. With **Auto Height**, vertical alignment doesn't change anything.
## Wrapping
* **Wrap** moves text to a new line when it reaches the width of its bounds.
* **No Wrap** keeps each paragraph on a single line.
Turning off wrapping works differently with each overflow option:

### Break
**Break** decides what happens to a single word that's too long to fit on a line. It only matters while the text wraps.
* **Break Word** is the default. A word moves to the next line, and is only split if it doesn't fit on a line by itself.
* **Normal** never splits a word. A word that's too long runs past the edge of the bounds.
* **Break All** splits words wherever the line ends, so every line is filled to the edge.
## Overflow
Overflow controls what happens when text in a **Fixed Size** box doesn't fit.
* **Visible**: The text runs past the bounds.
* **Hidden**: Lines that don't fit are hidden. Partly visible lines are hidden too.
* **Clipped**: The text is cut off at the bounds, including partly visible lines.
* **Ellipsis**: The text is cut off and ends with an ellipsis (…). In right-to-left text, the ellipsis appears on the left, where the line ends.
* **Fit**: The text is scaled down until it fits, keeping its line breaks. Turn on **Maintain baseline** to keep the first line's baseline in place as it scales.
* **Fit Font Size**: The font size is reduced until the text fits, and the text is laid out again at the new size, so its line breaks can change.

## Spacing and trim
### Paragraph spacing
**Paragraph Spacing** adds space between paragraphs. To change the space between lines, set the line height in the [text style](/docs/editor/text/text-styles).
### Trim
By default, text bounds include the space a font reserves above and below its letters. **Trim** removes that space, so the bounds hug the letters and the text lines up with other objects more easily. Set the top and bottom separately.
* **Top**:
* **None** keeps the font's full height above the text.
* **Cap** trims to the top of capital letters.
* **Ex** trims to the top of lowercase letters, such as "x".
* **Bottom**:
* **None** keeps the font's full depth below the text.
* **Alphabetic** trims to the baseline, the line the letters sit on.
* **Text** trims to the bottom of the text, including descenders like "g" and "y".


## Align origin to baseline
Turn on **Align origin to baseline** to put the text's origin on the baseline of its first line. This makes it easier to line text up with other objects, or keep its baseline in place as it changes size.

## Highlight text runs
Turn on **Highlight text runs** to tint each [run](/docs/editor/text/text-runs) in a different color on the stage, so you can see where one ends and the next begins. It only affects the editor.
## Flatten to shape
**Flatten to Shape** converts the text into vector paths that you can edit like any other shape. The result is no longer text, so you can't edit its content, and any keys on the text are removed.
> [!NOTE]
>
> Flattening text can create a lot of geometry. If you're flattening text to avoid embedding a font, keep it as text instead and export only the [glyphs you use](/docs/editor/text/fonts#export-options).
# Text Runs
Source: https://rive.app/docs/editor/text/text-runs
[YouTube video player](https://www.youtube.com/embed/UE23Agn1DZ0)
Runs allow you break your text up into sections — typically, they're used to apply a variety of styles to a single block of text. Whilst most tools manage text runs behind the scenes, Rive exposes them for greater control when dynamically changing text at runtime.
A Text object acts as a parent that can contain multiple Text Runs as children. Each Text Run represents a specific portion of the Text object and can have its own value and Text Style, allowing it to be targeted at runtime.
> [!NOTE]
>
> A Text Run may only have one Text Style applied at a time.
For example, an animation might greet a user with "Welcome back, username". By making "username" its own Text Run, you can give it a different style and [update it at runtime](/docs/runtimes/data-binding) with the user's name.

***
## Creating a Text Run
To create a Run, select the desired portion of text and select the 'Run from Selection' button in the Inspector. You can see Text Runs listed beneath the text object in the hierarchy.
Double click or press `Enter` with the text box selected to start editing text.
Toggle the 'Highlight Text Runs' option in the inspector for a visual guide of your current Text Runs. Hovering a run in the hierarchy also highlights its location within the text.

***
## Managing Text Runs
Select a Text Run in the hierarchy for inspector options:
* **Text Value:** Update the text value for the run. Key this value in [animate mode](/docs/editor/fundamentals/design-vs-animate-mode).
* **Edit Text Run:** Initiate the text editor with the run pre-selected.
* **Merge with Next:** Combine the selected run with the next run.
* **Merge with Previous:** Combine the selected run with the previous run.
* **Delete text Run:** Delete the run and its contents.
* **Style:** Assign one of the Text Styles defined on the text object. Key this value in [animate mode](/docs/editor/fundamentals/design-vs-animate-mode).

***
## Building runs from a list
You can build a Text object's runs from a [view model list](/docs/editor/data-binding/lists). Each item in the list becomes a run, after the runs you created in the editor. The item supplies the run's text and style.
**Step 1**
In the **Data** panel, click **+** and choose **View Model** > **Templates** > **Text Run**. This creates a view model with a **Text Content** property for the run's text and a **Text Style** property for its style.
**Step 2**
Add a list property that uses that view model to the view model your artboard is bound to.
**Step 3**
Select the Text object and use **Bind** at the bottom of the **Text Runs** section in the Inspector to bind the list.
Set an item's **Text Style** to the name of one of the Text object's styles. If no style has that name, the run uses the Text object's first style.
Runs created from a list don't appear in the Inspector, so you can't edit them there. Change the list items instead.
# Text Styles
Source: https://rive.app/docs/editor/text/text-styles
Define fonts, sizes, spacing, and paints for text, then apply them to individual text runs.
[YouTube video player](https://www.youtube.com/embed/FeUOLDzvSDw)
A text style defines how text looks: its font, size, spacing, and paints. Each style belongs to a Text object, and you can apply it to one or more of that object's [text runs](/docs/editor/text/text-runs). Use several styles in the same Text object to mix looks within a single block of text, or key between styles in an animation.
Text styles can only be applied to runs in the Text object where they're defined. You can't share a style across Text objects or files.
## Text style properties
Each text style includes these properties:
* **Font** and **weight**: The font family and the weight or style, such as Regular or Bold.
* **Font Size**: The size of the text.
* **Letter Spacing**: The space between characters.
* **Line Height**: The space between lines. Set it to **Auto** to use the font's default.
* **Fills and strokes**: The paints applied to the text itself.
* **Background Fill** and **Background Stroke**: Paints drawn behind the text, with a **Corner** radius to round the background.

### Font options
Some fonts include variable axes, such as weight, width, or slant, or OpenType features, such as ligatures and stylistic alternates. For these fonts, an options button appears on the text style in the Inspector. Click it to open **Font Options**:
* **Variables** sets the font's variable axes. For example, set weight to any value in the font's range instead of choosing a fixed weight.
* **Features** turns the font's OpenType features on or off.
You can animate variable axes. Open **Font Options** in [Animate mode](/docs/editor/fundamentals/design-vs-animate-mode) to key the available axes.
### Animating the font
In [animate mode](/docs/editor/fundamentals/design-vs-animate-mode), picking a different font or style (like Bold) for a Text Style adds a key instead of changing the font in the design. On a variable font, the key also keeps the style it was set with.
Exported files include every font used by a key.
## Creating text styles
Each new Text object starts with one text style. To add another, select the Text object and click **+** in the **Text Styles** section of the Inspector.
## Applying a style to a text run
You can apply a text style to a run in either of two ways:
* Select the text run in the Hierarchy, then choose a style from the **Style** dropdown in the Inspector.
* Click **Apply to Runs** next to the style in the Inspector, then select a run from the menu. Hover over each option to preview the result on the stage.

## Editing styles across several texts
When you select several Text objects, the Inspector shows each of their styles as its own card. To edit matching styles together, click the group button in the **Text Styles** header. The button only appears when some styles match.
Styles match when they use the same font and style, such as Inter Bold. Matching styles merge into one card that shows how many styles it holds. Any edit you make on a grouped card applies to every style in it. Click the button again to show each style separately.
# Dependencies Graph
Source: https://rive.app/docs/editor/workflows/dependency-graph
Use the Dependency Graph to visualize relationships between elements in your file
## Show dependencies
To show dependencies, select an item and press **D**. Rive displays arrows connecting the selected item to its parent and child dependencies.

Dependency arrows are color coded based on the type of relationship.
For example, if the rotation of `NEW_sticker` is controlled by the rotation of `Icon` through a constraint, Rive shows that dependency with a yellow arrow.

## Filtering
Use the dependency options to filter which relationships are shown. This is helpful when an element has many connections and you only want to focus on specific dependency types.
The dot next to each dependency type matches its arrow color. A blue dot on the options button means some types are hidden.

# Feature Support
Source: https://rive.app/docs/feature-support
As the Rive Editor evolves, some new features require updates to the Rive runtimes. In certain cases, this may introduce new or modified APIs. We recommend staying on the latest runtime version to ensure compatibility, bug fixes, and performance improvements.Use the table below to verify whether a feature used in your `.riv` file is supported by your target runtime.> [!WARNING]
>
> Certain features require the use of the Rive Renderer at runtime. See our
> documentation on [choosing a renderer](/docs/runtimes/choose-a-renderer/).When a feature requires API changes, migration notes will be included below.## Feature support by runtime
\> \[accordion] Web
\>
\> \* \*\*WebGL2\*\* (\`@rive-app/webgl2\`): The recommended package for most web projects. Uses the Rive Renderer, which support every Rive Editor feature.
\> \* \*\*Canvas\*\* (\`@rive-app/canvas\`): Uses the browser's Canvas2D renderer. Some rendering features, such as Layer Masks and Bitmap Cache, are not supported.
\> \* \*\*Canvas Lite\*\* (\`@rive-app/canvas-lite\`): Uses the same API as \`@rive-app/canvas\`, but excludes certain features to reduce bundle size.
\>
\> See \[Canvas vs WebGL2]\(/runtimes/web/canvas-vs-webgl) for the tradeoffs.
\>
\>
\> \\\\\*\*Feature\*\*\ \ \
\> \ \
\> \[accordion] React
\>
\> \* \*\*WebGL2\*\* (\`@rive-app/react-webgl2\`): The recommended package for most React projects. Uses the Rive Renderer, which support every Rive Editor feature.
\> \* \*\*Canvas\*\* (\`@rive-app/react-canvas\`): Uses the browser's Canvas2D renderer. Some rendering features, such as Layer Masks and Bitmap Cache, are not supported.
\> \* \*\*Canvas Lite\*\* (\`@rive-app/react-canvas-lite\`): Uses the same API as \`@rive-app/react-canvas\`, but excludes certain features to reduce bundle size.
\>
\> See \[Canvas vs WebGL2]\(/runtimes/web/canvas-vs-webgl) for the tradeoffs.
\>
\>
\> \\\\\*\*Feature\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> Versions refer to the \`@rive-app/react-native\` package, built with Nitro.
\>
\> GPU Canvas is supported on iOS in \`0.5.3\` and later, and on Android in \`0.5.7\` and later. It is disabled by default. Enable it before loading any Rive files:
\>
\> \`\`\`ts theme=\{null}
\> import \{ RiveRuntime } from '@rive-app/react-native';
\>
\> RiveRuntime.setGPUCanvasEnabled(true);
\> \`\`\`
\>
\> This setting applies to every Rive file in the app. Changes made after file loading begins are ignored. If you \[override the native SDK versions]\(/runtimes/react-native/native-version-customization), GPU Canvas requires Rive iOS \`6.25.0\` or later and Rive Android \`11.14.2\` or later.
\>
\> Layer Masks require GPU Canvas on both iOS and Android. With the bundled native SDKs, they are supported on iOS in \`0.5.3\` and later, and on Android in \`0.5.13\` and later. Layer Masks are not supported in iOS simulators. If you override the native SDK versions, use Rive iOS \`6.28.0\` or later and Rive Android \`11.16.3\` or later.
\>
\> Semantics are supported on iOS in \`0.5.0\` and later. Import \`Semantics\` from \`@rive-app/react-native\` and set \`semantics=\{Semantics.Automatic}\` on \`RiveView\` to enable accessibility when VoiceOver is running.
\>
\> > \\\[!NOTE]
\> >
\> > In \`0.5.0\` and later, the deprecated event and text-run methods are unavailable. Use \[data binding]\(/runtimes/react-native/data-binding) to listen for triggers and update text instead.
\>
\>
\> \\\\\*\*Feature\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> \\\\\*\*Feature\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> > \\\[!WARNING]
\> >
\> > Some rendering features require \[GPU Canvas]\(/runtimes/apple/gpu-canvas) (the deferred renderer) on Apple platforms. These are marked "GPU Canvas required" in the table below.
\>
\>
\> \\\\\*\*Feature\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> > \\\[!WARNING]
\> >
\> > Some rendering features require \[GPU Canvas]\(/runtimes/android/gpu-canvas) on Android. These are marked "GPU Canvas required" in the table below.
\>
\>
\> \\\\\*\*Feature\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> \\\\\*\*Feature\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> \\\\\*\*Feature\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> \\\\\*\*Feature\*\*\ \ \
\> \ \
## Runtime support by featureA green checkmark (✅) indicates that a feature is supported in all relevant runtimes.
A yellow circle (🟡) indicates that support varies by runtime or renderer.Differences may reflect:* Platform or SDK limitations where a feature cannot be supported
* Staggered releases as features roll out across runtimes, or
* Lightweight (“lite”) builds that intentionally omit some features to reduce package size.> [!NOTE]
>
> A feature may still be considered fully supported even if it is unavailable in legacy runtimes.
\> \[accordion]
\>
\> Layer Masks require the Rive Renderer.
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> Fills and strokes that paint with an artboard.
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> See \[Meshes]\(/editor/manipulating-shapes/meshes) and \[Components]\(/editor/fundamentals/components#deform).
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> Fills and strokes that paint with an image.
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> Strokes with \*\*Position\*\* set to \*\*Inside\*\* or \*\*Outside\*\* in \*\*Stroke Options\*\*.
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> GPU Canvas enables 3D and shader content. See each runtime section for more details.
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> On Apple, this feature requires the Swift Concurrency API. See \[Global View Models]\(/runtimes/apple/data-binding#global-view-models).
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> On Apple, this feature requires the Swift Concurrency API. See \[Data Binding]\(/runtimes/apple/data-binding).
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> Accessibility voice over support with \[Semantics]\(/editor/accessibility/semantics).
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> Support for Rive files with \[AnimaScript]\(https\://rive.app/rasc/docs/introduction.html) scripts. For Luau, see Scripting.
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> Support for Rive files with Luau \[Scripting]\(/scripting).
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> Data binding lists, images, and artboards were added after initial data binding support.
\>
\> See \[Data Binding Overview]\(/editor/data-binding/overview) and \[Data Binding for Runtimes]\(/runtimes/data-binding).
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> See \[Data Binding Overview]\(/editor/data-binding/overview) and \[Data Binding for Runtimes]\(/runtimes/data-binding).
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> See \[N-Slicing]\(/editor/layouts/n-slicing).
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> Allows Rive to automatically update the artboard size as the underlying view/canvas/widget/texture size changes. See \[Layouts]\(/editor/layouts/layouts-overview).
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> Allows Rive to use a fallback font if a glyph is not available. A default font is automatically chosen, or you can optionally configure the desired fallback font based on various options. See \[Fallback Fonts]\(/runtimes/text#fallback-fonts).
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> See \[Rive Events]\(/runtimes/rive-events) and \[Audio Events]\(/editor/events/audio-events).
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> See \[Loading Assets]\(/runtimes/loading-assets).
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> See \[Text]\(/runtimes/text).
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
## Legacy**Legacy runtimes**
\> \[accordion]
\>
\> > \\\[!WARNING]
\> >
\> > The \`@rive-app/webgl\` runtime is deprecated as of \`v2.37.0\`. Use \`@rive-app/webgl2\` (recommended for most content), or \`@rive-app/canvas\`.
\>
\>
\> \\\\\*\*Feature\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> > \\\[!WARNING]
\> >
\> > The \`@rive-app/react-webgl\` runtime is deprecated as of \`v4.30.0\`. Use \`@rive-app/react-webgl2\` (recommended for most content), or \`@rive-app/react-canvas\`.
\>
\>
\> \\\\\*\*Feature\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> > \\\[!WARNING]
\> >
\> > The \`rive-react-native\` runtime is deprecated. For better performance and the latest features, use \`rive-nitro-react-native\`.
\> >
\> > \[Migration guide]\(/runtimes/react-native/migration-guide#migrating-from-rive-react-native-to-\@rive-app/react-native)
\>
\>
\> \\\\\*\*Feature\*\*\ \ \
\> \ \
**Deprecated features**
\> \[accordion]
\>
\> > \\\[!WARNING]
\> >
\> > Listening to \[Rive Events]\(/runtimes/rive-events) at runtime is deprecated and will be removed in future versions.
\> >
\> > Use \[Data Binding]\(/runtimes/data-binding) to listen for triggers or changes to properties instead.
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
\> \[accordion]
\>
\> > \\\[!WARNING]
\> >
\> > Setting text, including \[nested text]\(/runtimes/text#read-update-nested-text-runs-at-runtime), at runtime is deprecated and will be removed in a future version.
\> >
\> > Instead, use \[Data Binding]\(/runtimes/data-binding) to update a string, which is bound to a text run.
\>
\>
\> \\\\\*\*Runtime\*\*\
\> \\*\*Version\*\*\ \ \
\> \ \
# Defold
Source: https://rive.app/docs/game-runtimes/defold
[Defold](https://defold.com/) is a free, cross-platform, game engine that has built-in support for Rive graphics, allowing you to easily incorporate Rive into your Defold games.
> [!NOTE]
>
> Rive integration is managed by the Defold team.
For more information on using Rive with Defold, please refer to the [official Defold documentation](https://defold.com/extension-rive/). There, you will find comprehensive guides on setting up Rive graphics and best practices for using them within the Defold engine.
### Rendering
Defold has integrated the [Rive Renderer](https://rive.app/renderer) natively, which means that Rive graphics in Defold are rendered by the same renderer used in the Rive Editor. This native integration offers several benefits:
* **Performance**: The Rive Renderer is custom-built for Rive content, for animation, and for runtime. Allowing you to draw an unprecedented amount of vector graphics with mega fast rendering. [Read more](https://rive.app/blog/rive-renderer-now-open-source-and-available-on-all-platforms).
* **Quality**: Graphics remain crisp and clear regardless of scale, resolution, or device.
* **Consistency:** Your graphic will look exactly the same in the Editor and at Runtime.
* **Feature support:** You'll also benefit from upcoming Rive features, such as blurs and shadows, that will only be possible through the Rive Renderer.
### Support
If you have any questions about Rive in Defold, feel free to explore their [community forums](https://forum.defold.com/) or reach out to their support. If you believe the issue to be with Rive, reach out to us on [our Community](https://community.rive.app/c/support/).
# Audio
Source: https://rive.app/docs/game-runtimes/unity/audio
Rive audio playback in Unity.
In the Unity runtime, audio playback from Rive files is automatically routed through Unity's audio system via the `AudioProvider` component, which wraps an `AudioSource` to mix Rive's audio output into the Unity audio pipeline.
> [!NOTE]
>
> Audio playback via `AudioProvider` is **not supported in WebGL builds**. On WebGL, Rive automatically falls back to system audio instead of routing through Unity's `AudioSource`.
## How it works
Each `RiveWidget` that plays a Rive file with audio needs access to an `AudioProvider`. By default, all widgets share a single **global** `AudioProvider` that is created automatically at runtime. No additional setup is required.
If you need more control (for example, to manage volume or audio mixer groups independently per widget), you can assign a **custom** `AudioProvider` to individual widgets.
## Global audio provider
The global `AudioProvider` is created automatically the first time a widget with audio needs it. It is shared across all `RiveWidget` instances that don't have a custom provider assigned.
This is the recommended setup for most projects, and no additional configuration is required.
## Custom audio provider
To use a custom `AudioProvider` for a specific widget:
**Step 1**
Add an `AudioProvider` component to a GameObject in your scene. The `AudioProvider` component requires an `AudioSource` on the same GameObject. Unity will add one automatically.
**Step 2**
Assign the `AudioProvider` to the **Custom Audio Provider** field on your `RiveWidget` in the Inspector.
You can also assign a custom provider at runtime via script:
```csharp theme={null}
[SerializeField] private RiveWidget m_riveWidget;
[SerializeField] private AudioProvider m_audioProvider;
private void Start()
{
m_riveWidget.CustomAudioProvider = m_audioProvider;
}
```
Setting `CustomAudioProvider` to `null` reverts the widget to using the shared global provider.
## Platform notes
| Platform | Behavior |
| - | - |
| Editor / Standalone | Audio routed through Unity's `AudioSource` via `AudioProvider` |
| iOS / Android | Audio routed through `AudioSource`; `Play()` is called automatically on start |
| WebGL | System audio is used; `AudioProvider` is not supported and will log a warning if added |
> [!WARNING]
>
> Adding an `AudioProvider` component to a WebGL build will produce a warning at runtime. The component has no effect on that platform, and audio will still play via the browser's system audio.
## AudioProvider component reference
| Property | Description |
| - | - |
| `AudioSource` | The `AudioSource` component used for audio playback. Required; automatically added with `AudioProvider`. |
# Best Practices
Source: https://rive.app/docs/game-runtimes/unity/best-practices
Performance and usage considerations for Rive in Unity.
Rive is designed to be efficient in Unity, but performance can still be affected by core factors like how much work happens every frame, how much memory is in use, and how much rendering overhead is required.
> [card] [General Rive best practices](/docs/getting-started/best-practices)
>
> Design-time and runtime guidance that applies across platforms.
> [card] [Unity components](/docs/game-runtimes/unity/components)
>
> Learn how Rive Panel, Rive Widget, and render target strategies work.
## Rive Panels and Render Textures
In Unity, **one Rive Panel renders into one Render Texture** by default. Every **Rive Widget** under a panel draws into that same Render Texture.
That's why, for UI:
* **Prefer fewer panels**: One (or a small number) of panels is usually best, especially on mobile.
* **Group widgets under a shared panel**: Multiple widgets under a single panel is typically more efficient than multiple panels.
### Compose UI in Rive
When you're getting started with Rive, it can be tempting to use it as a simple replacement for individual UI components (for example, building a single “Rive Button”, instancing it many times, and then assembling it in uGUI/UIToolkit). In Unity, this often creates unnecessary widget/panel/render texture overhead.
For most projects, the recommended approach is to build your full menu (or at least larger chunks of a screen) in Rive, render it single widget/panel, and drive it with data binding.
### Prefer Data Binding with lists for dynamic content
If your UI needs to create and remove items dynamically (for example: inventories, chat feeds, spawning characters), prefer using **data binding list properties** instead of creating lots of separate Rive Widgets.
Using lists keeps repeated graphics **inside a single Rive file / widget**, while still letting you add/remove/swap items at runtime through your Unity code.
See:
* Concepts + examples: [Data binding lists](/docs/game-runtimes/unity/data-binding#lists)
* Editor setup: [Lists in the editor](/docs/editor/data-binding/lists)
### Screen Space UI vs World Space UI
* **Screen space UI**: You can usually structure your UI so a single panel covers the whole screen.
* **World space UI / VR**: If your UI exists in the world and needs different sizes, transforms, or visibility rules, you may end up needing more panels and more careful control of render textures.
If you have a real use case for many panels (for example, lots of world-space UI surfaces), look at **Render Target Strategies**:
* **Atlas Render Target Strategy**: Packs multiple panels into a shared atlas texture to reduce texture count.
* **Pooled Render Target Strategy**: Reuses textures to reduce allocation churn when panels appear/disappear frequently.
See: [Render Target Strategies](/docs/game-runtimes/unity/components#render-target-strategies).
## One Rive file vs multiple files
For multi-screen UI, this usually means choosing between:
* **One larger `.riv` file** that contains multiple screens (often as components), with transitions and logic handled inside Rive.
* **Multiple `.riv` files** (for example, one per menu) that you enable or instantiate and swap via C#.
The best structure depends on both performance goals and how you want to author and maintain your files.
#### One larger file
* **Pros**: Keep a full UI flow in one place, drive transitions inside Rive, and test the entire experience in the Rive Editor. The file could be loaded once (e.g. at the start of the game) and can be reused across multiple screens or menus.
* **Tradeoff**: The entire file (including its embedded assets) stays in memory even if you're only using part of it or displaying a single artboard.
#### Multiple files
For example, one per screen or menu:
* **Pros**: Load/unload screen-specific UI to save memory. This works well when different screens have different asset needs.
* **Tradeoffs**:
* Transitions between screens typically happen in C# (outside Rive).
* Be sure to **disable/destroy** widgets you aren't using so they aren't advancing or rendering.
#### Hybrid approach: Data Binding with artboard slots
If you want modular loading *and* want to stay in a single widget/panel, a hybrid approach can work well:
* Keep a “main” UI file that owns the overall layout and interaction flow.
* Use data binding to load other artboards (stored in other `.riv` files) into slots at runtime.
This lets you keep UI modular while still rendering through a shared panel and widget.
The main tradeoff here is that you may need to create more files and manage them more carefully, and you may need to create more data binding properties and logic to manage the different artboards.
See:
* Unity: [Data Binding](/docs/game-runtimes/unity/data-binding)
* Concepts: [Data binding artboards](/docs/game-runtimes/unity/data-binding#artboards)
## Embedded vs referenced assets
Most projects can start with embedded assets and only optimize when needed. Referenced assets become useful when you need better reuse and control.
* **Embedded assets**: Simple workflow; everything is inside the `.riv` file.
* **Referenced assets**: Useful when you reuse the same fonts/images/audio across multiple `.riv` files, or when you want to swap assets at runtime without duplicating them across files.
Referenced assets can also help you:
* **Avoid duplicating assets** when the same images/fonts are used across multiple Rive files.
* **Swap to lower-resolution assets** on memory-constrained devices (keeping the same aspect ratio). If your Rive layout is set up to adapt, the graphic can adjust cleanly.
See: [Loading Assets (Unity)](/docs/game-runtimes/unity/loading-assets).
# Components
Source: https://rive.app/docs/game-runtimes/unity/components
The Rive Unity package includes components to help you integrate Rive into your project quickly and easily. These components are a high-level abstraction over the [low-level API](/docs/game-runtimes/unity/fundamentals), handling rendering and pointer input, and providing a unified way of working with Rive across render pipelines.
We recommend working with these components unless you have specific rendering needs or need more control over where Rive fits into your graphics pipeline, in which case you can use the low-level API.
## Rive Panel
The Rive Panel is the foundation for displaying Rive graphics in Unity. It acts as a viewport that manages and renders a collection of Rive widgets to a render texture, with the panel's dimensions determining the render target's size.
The panel renders multiple widgets to a single render texture, which means you draw different Rive files and artboards to one texture by placing multiple Rive Widgets under the same panel. This is more performant than using multiple panels as each panel renders to a separate texture by default.
#### Setup
Create an instance: Right-click in the scene hierarchy `→ Rive → Rive Panel`
> [!WARNING]
>
> A Rive Panel simply handles drawing the graphics to a texture. You'll need to use the Rive Panel **with** a [Panel Renderer](/docs/game-runtimes/unity/components#panel-renderers) to display the texture.
**Configuration**
| Property | Description |
| - | - |
| Custom Render Target Strategy | The strategy to use for rendering the panel. By default, each panel renders to a single RenderTexture that matches the panel's dimensions. You can provide a different strategy to render to a pool of textures or share a texture between panels. |
| Update Mode | Controls how the panel updates widgets: `Auto` for automatic updates each frame, or `Manual` for explicit control through `Tick()`. |
| Disable Editor Preview | Use this to prevent the panel from rendering in Edit mode in the Unity Editor |
| Draw Optimization | Controls when the panel redraws its render texture. `Draw When Changed` (default) redraws only when an artboard changed, or when Unity triggers a redraw such as a layout or size change. `Always Draw` redraws every frame. Panels that share an atlas render target redraw every frame if any of them uses `Always Draw`. |
| Multitouch Support | When `Disabled`, the panel collapses all input to a single pointer for legacy behavior. When `Enabled`, multiple pointers are tracked independently. |
**Properties**
| Property | Description |
| - | - |
| Widget Container | The RectTransform that holds the panel's widgets. |
| Widgets | A read-only list of widgets managed by the panel. |
| Render Texture | The current render texture where widgets are drawn. |
| Scale In RenderTexture | The scale of the panel within its render texture. Returns `Vector2.one` if no render strategy is set. |
| Offset In Render Texture | The offset of the panel within its render texture. Returns `Vector2.one` if no render target strategy is set. |
| Is Rendering | Whether the panel is currently registered with a render target strategy and actively rendering. |
**Public Methods**
| Name | Description |
| - | - |
| Tick(float deltaTime) | Updates all widgets in the panel. Called automatically in Auto mode. You only need to call this if the `Update Mode` is set to `Manual` |
| StartRendering() | Begins rendering the panel if it isn't already rendering to a render texture. |
| StopRendering() | Stops rendering the panel if it's currently rendering to a render texture |
| SetDimensions(Vector2 dimensions) | Sets the width and height of the panel. |
| RegisterInputProvider(IPanelInputProvider provider) | Registers a custom input provider for handling pointer events. |
| UnregisterInputProvider(IPanelInputProvider provider) | Removes a previously registered input provider. |
## Rive Widget
The Rive Widget is the primary component for displaying Rive artboards in Unity. It handles loading Rive files either from assets during edit time or from runtime-loaded files (useful when loading Rive content from a server or Addressables). The component manages artboard and state machine setup, automatically configuring everything needed to display your graphic.
#### Setup
Create an instance: Right-click in the scene hierarchy `→ Rive → Widgets → RiveWidget`
> [!NOTE]
>
> Rive Widgets must be placed under a RivePanel to be displayed.
**Configuration**
| Field | Description |
| - | - |
| Asset | The Rive asset (.riv) to load. |
| Artboard Name | The name of the artboard to load from the Rive file. |
| State Machine Name | The name of the state machine to load from the selected artboard. |
| Hit Test Behaviour | How pointer events are handled (Opaque, Translucent, Transparent, None). |
| Fit | How the artboard should fit within the widget's bounds. See the [Fit docs](/docs/game-runtimes/unity/layouts#the-fit-mode) for more details about the available options. |
| Alignment | How to align the artboard within the widget's bounds |
| Layout Scale Factor | Scale multiplier used when in Layout fit mode. |
| Layout Scaling Mode | How the widget scales in Layout mode (`ReferenceArtboardSize`, `ConstantPhysicalSize` and `ConstantPixelSize`). |
| Fallback DPI | DPI value to use when screen DPI is unavailable |
| Reference DPI | Target DPI for scaling calculations |
| Speed | Controls the widget's playback speed. A value of 1 is normal speed, 2 is double speed, 0.5 is half speed |
**Properties**
| Name | Description |
| - | - |
| File | The currently loaded Rive file instance. |
| Artboard | The currently loaded artboard instance. |
| State Machine | The currently loaded state machine instance. |
| Status | Current status of the widget (Uninitialized, Loading, Loaded, Error) |
| BindingMode | Determines how the widget should handle binding to a ViewModel instance: Auto Bind Default, Auto Bind Selected, or Manual. Auto Bind modes also bind default instances for any [global view models](/docs/game-runtimes/unity/data-binding#global-view-models) in the file. |
| ViewModelInstanceName | The name of the ViewModel instance to bind to when BindingMode is set to Auto Bind Selected. |
**Events**
| Name | Description |
| - | - |
| OnRiveEventReported | Triggered when a Rive event is reported from the Rive graphic. |
| OnWidgetStatusChanged | Triggered when the widget's status changes (e.g., from Loading to Loaded, or Error). |
**Public Methods**
| Name | Description |
| - | - |
| Load(File file) | Loads a Rive file using the default artboard and state machine. |
| Load(File file, string artboardName, string stateMachineName) | Loads a Rive file with specified artboard and state machine. |
| Load(Asset asset) | Loads from a Rive asset using the default artboard and state machine. The Rive Widget manages the lifecycle of the loaded file and cleans up the file when the widget is destroyed or when a new asset is passed in. |
| Load(Asset asset, string artboardName, string stateMachineName) | Loads from a Rive asset with specified artboard and state machine. The Rive Widget manages the lifecycle of the loaded file and cleans up the file when the widget is destroyed or when a new asset is passed in. |
> [!WARNING]
>
> If you use any Load methods that accept a `File` instance, you're responsible for disposing of the File instance when you no longer need it. This is not the case when loading from an `Asset` as the Rive Widget manages the lifecycle of the underlying file (loading and disposing).
## Procedural Rive Widget
The Procedural Rive Widget enables runtime generation of graphics using the Rive's Renderer. This component lets you create graphics programmatically using Rive's drawing primitives (paths and paints, etc.).
See [this example](https://github.com/rive-app/rive-unity/blob/0765c81e1b68e77fcbf0e62afee7290eff400d17/tests/package/PlayModeTests/Components/Goldens/TestPanels/TestProceduralDrawing.cs) for a practical implementation of a procedural drawing.
#### Setup
Create an instance: Right-click in the scene hierarchy `→ Rive → Widgets → Procedural Rive Widget`
> [!NOTE]
>
> Procedural Rive Widgets must be placed under a RivePanel to be displayed.
**Configuration**
| Property | Description |
| - | - |
| Procedural Drawing | ProceduralDrawing instance that defines what to draw. |
| Hit Test Behavior | How pointer events are handled (Opaque, Translucent, Transparent, None). |
**Properties**
| Name | Description |
| - | - |
| Status | Current status of the widget (Uninitialized, Loading, Loaded, Error). |
**Events**
| Name | Description |
| - | - |
| OnWidgetStatusChanged | Triggered when the widget's status changes (e.g., from Loading to Loaded, or Error). |
**Public Methods**
| Name | Description |
| - | - |
| Load(ProceduralDrawing proceduralDrawing) | Loads a new procedural drawing into the widget. |
## Panel renderers
Panel renderers connect RivePanel's render texture to Unity's display systems. By separating rendering logic from display concerns, we can support different rendering contexts (UI, world space, etc.) while keeping the core Rive functionality consistent.
Each renderer type specializes in a specific Unity rendering pathway, handling details like input systems and render order automatically.
### Rive canvas renderer
The Rive Canvas Renderer displays Rive content within Unity's UI system (uGUI). It automatically configures the necessary Canvas components and handles UI-specific concerns like proper render order and raycasting.
> [!NOTE]
>
> The Rive Canvas Renderer controls the size of the Rive Panel based on the uGUI Canvas it is being displayed under.
You can also create a Rive Panel that has been automatically configured to use this component by right-clicking in the scene hierarchy and navigating to the `Rive > Rive Panel (Canvas)`
#### Requirements
* Requires an EventSystem in the scene for pointer input
* Requires a GraphicRaycaster on the Canvas for pointer input
* The Rive Panel must be under a uGUI canvas
* This component must be placed on the same game object as the Rive Panel
#### Configuration
| Property | Description |
| - | - |
| Pointer Input Mode | Controls whether the renderer accepts pointer input (Enable/Disable). |
| Custom Material | A custom UI material to use when rendering the Rive graphic. |
| Match Canvas Resolution | Whether to match the canvas resolution to the RivePanel's resolution. This is useful for keeping the Rive graphic crisp when using a `Canvas Scaler`. By default, the RivePanel resolution is defined by its rect transform's width and height. Setting this to `true` will result in the RivePanel being rendered at a higher resolution than the panel's rect transform's size if needed. This feature is currently only supported when the RivePanel uses the `SimpleRenderTargetStrategy`, which is the default strategy used if none is provided. |
#### Properties
| Name | Description |
| - | - |
| Rive Panel | The panel being rendered. |
### Rive texture renderer
Rive Texture Renderer projects Rive content onto materials in your 3D scene. It bridges the gap between Rive's 2D rendering system and Unity's 3D material system, making it easy to apply Rive content to any mesh in your scene.
#### Requirements
* Must be placed on a GameObject with a MeshRenderer on it. e.g. a Cube, Plane, Quad, or Capsule.
* Requires an EventSystem in the scene for pointer input
* Requires a PhysicsRaycaster on the camera for pointer input in 3D space
* Target GameObject needs a MeshCollider for pointer input
#### Configuration
| Field | Description |
| - | - |
| Renderer | The Unity Renderer component (e.g., MeshRenderer,) that will display the Rive content. |
| Material Texture Assignment Mode | Controls which texture properties are set to the Rive Panel's render texture: MainTexture sets the `_MainTex` property on the material. The `TextureProperties` option lets you select multiple specific texture properties. |
| Visibility Optimization | Determines if the RivePanel should stop rendering when the mesh is not visible to the camera. |
| Pointer Input Mode | Controls whether the renderer accepts pointer input (Enable/Disable). |
#### Properties
| Name | Description |
| - | - |
| Rive Panel | The panel being rendered to materials. |
**Public Methods**
| Name | Description |
| - | - |
| SetPanel(IRivePanel panel) | Assigns a new panel to render. |
| RefreshMaterials() | Updates material references after material changes. |
## Render Target strategies
Render Target Strategies control how **Rive Panels** render to textures. They determine whether panels get individual textures or share a texture atlas, and handle details like texture creation, panel arrangement, and memory management.
### Simple Render Target Strategy
The `Simple Render Target Strategy` is the default rendering approach for **Rive Panels**, creating a dedicated render texture for each panel. It is automatically added to a Rive Panel if no custom strategy is provided.
This one-to-one mapping between panels and textures provides straightforward memory management.
> [!NOTE]
>
> The component must be attached to the same GameObject as its RivePanel
**Configuration**
| Field | Description |
| - | - |
| Panel | The RivePanel this strategy manages (automatically set when on same GameObject). |
| Draw Timing | When rendering occurs: `Batched` (once per frame) or `Immediate` (instant updates). |
**Properties**
| Name | Description |
| - | - |
| DrawTiming | Current draw timing mode. |
### Atlas Render Target Strategy
The Atlas Render Target Strategy enables multiple panels to share a single texture atlas, optimizing memory usage and draw calls.
By default, it uses a simple shelf-packing algorithm to efficiently arrange panels within the atlas, automatically growing the texture as needed while respecting maximum size constraints.
#### Setup
1. Create an instance: Right-click in the scene hierarchy `→ Rive → Render Target Strategies → Atlas Render Target Strategy`
* Assign to panels: Drag the strategy into the `Custom Render Target Strategy` field on desired panels
* (Optional) Configure atlas parameters like starting size and resolution limits
#### Notes
* Panels sharing the same strategy instance share the same atlas texture
* Create multiple strategy instances to group panels into different atlases
**Configuration**
| Field | Description |
| - | - |
| Starting Size | Initial dimensions of the atlas texture (e.g., 1024x1024). |
| Max Atlas Size | Maximum dimensions the atlas can grow to (e.g., 2048x2048). |
| Max Resolution Per Panel | Maximum resolution for any single panel. Larger panels are scaled down (e.g., an 800x400 panel with max value of 512 becomes 512x256). |
| Padding | Space between panels in the atlas to prevent texture bleeding. |
| Draw Timing | When rendering occurs: `Batched` (once per frame) or `Immediate` (instant updates). |
| Custom Atlas Packing Provider | Optional custom packing algorithm (defaults to shelf packing if not specified). |
**Properties**
| Name | Description |
| - | - |
| Packing Strategy | Current strategy used for arranging panels in the atlas. |
| Draw Timing | Current draw timing mode. |
**Public Methods**
| Name | Description |
| - | - |
| Configure(Vector2Int startingSize, Vector2Int maxSize, int maxResPerPanel, int padding) | Sets up atlas parameters before initialization. |
### Pooled Render Target Strategy
The **Pooled Render Target Strategy** optimizes memory usage by maintaining a pool of reusable render textures. Instead of creating a new texture for each panel or sharing a single atlas, this strategy draws panels to textures from a managed pool, recycling them as needed.
This approach is particularly useful for scenes with dynamic UI elements that appear and disappear frequently. For example, in a game with popup menus or tooltips that show Rive graphics, the strategy can reuse textures as UI elements are shown and hidden, avoiding constant texture allocation and deallocation.
#### Configuration
| Field | Description |
| - | - |
| Pooled Texture Size | Size of textures in the pool (all pooled textures share these dimensions). If a given Rive Panel doesn't match the texture's aspect ratio, the panel will be resized to fit within the texture while maintaining its aspect ratio. |
| Initial Pool Size | The initial allocated size of the pool. |
| Max Pool Size | Maximum number of textures the pool can contain. |
| Pool Overflow Behavior | How to handle requests when pool is full: `Flexible` (create temporary textures) or `Fixed` (reject new panels). |
| Draw Timing | When rendering occurs: `Batched` (once per frame) or `Immediate` (instant updates). |
#### Properties
| Name | Description |
| - | - |
| Pool Overflow | Current overflow behavior setting. |
| Pooled Texture Size | Current texture dimensions used by the pool. |
| Initial Pool Size | Current initial pool capacity. |
| Max Pool Size | Current maximum pool size. |
| Draw Timing | Current draw timing mode. |
#### Public methods
| Name | Description |
| - | - |
| Configure(Vector2Int textureSize, int initialSize, int maxSize, PoolOverflowBehavior behavior) | Sets up pool parameters (must be called before the first Rive Panel is registered). |
# Data Binding
Source: https://rive.app/docs/game-runtimes/unity/data-binding
Connect your code to bound editor elements using View Models
Before engaging with the runtime data binding APIs, it is important to familiarize yourself with the core concepts presented in the [Overview](/docs/editor/data-binding/overview).
# View Models
View models describe a set of properties, but cannot themselves be used to get or set values - that is the role of [view model instances](#view-model-instances).
To begin, we need to get a reference to a particular view model. This can be done either by index, by name, or the default for a given artboard, and is done from the Rive file. The default option refers to the view model assigned to an artboard by the dropdown in the editor.
> [!NOTE]
>
> These APIs are only needed when the `Data Binding Mode` on the RiveWidget is set to `Manual`.
>
> Otherwise, you can configure view model binding directly in the Unity Inspector under the Data section.
```csharp theme={null}
private void OnEnable()
{
riveWidget.OnWidgetStatusChanged += HandleWidgetStatusChanged;
}
private void OnDisable()
{
riveWidget.OnWidgetStatusChanged -= HandleWidgetStatusChanged;
}
private void HandleWidgetStatusChanged()
{
if (riveWidget.Status == WidgetStatus.Loaded)
{
File file = riveWidget.File;
// Get reference by name
ViewModel viewModel = file.GetViewModelByName("My View Model");
// Get reference by index
for (int i = 0; i < file.ViewModelCount; i++)
{
ViewModel indexedVM = file.GetViewModelAtIndex(i);
}
// Get reference to the default view model for an artboard
ViewModel defaultVM = riveWidget.Artboard.DefaultViewModel;
}
}
```
# View Model Instances
Once we have a reference to a view model, it can be used to create an instance. When creating an instance, you have four options:
1. Create a blank instance - Fill the properties of the created instance with default values as follows:
| Type | Value |
| - | - |
| Number | 0 |
| String | Empty string |
| Boolean | False |
| Color | 0xFF000000 |
| Trigger | Untriggered |
| Enum | The first value |
| Image | No image |
| Font | No font |
| Artboard | No artboard |
| List | Empty list |
| Nested view model | Null |
2. Create the default instance - Use the instance labelled "Default" in the editor. Usually this is the one a designer intends as the primary one to be used at runtime.
3. Create by index - Using the order returned when iterating over all available instances. Useful when creating multiple instances by iteration.
4. Create by name - Use the editor's instance name. Useful when creating a specific instance.
> [!NOTE]
>
> In some samples, due to the wordiness of "view model instance", we use the abbreviation "VMI", as well as "VM" for "view model".
> [!NOTE]
>
> These APIs are only needed when the `Data Binding Mode` on the RiveWidget is set to `Manual`.
>
> Otherwise, you can configure view model binding directly in the Unity Inspector under the Data section.
```csharp theme={null}
private void OnEnable()
{
riveWidget.OnWidgetStatusChanged += HandleWidgetStatusChanged;
}
private void OnDisable()
{
riveWidget.OnWidgetStatusChanged -= HandleWidgetStatusChanged;
}
private void HandleWidgetStatusChanged()
{
if (riveWidget.Status == WidgetStatus.Loaded)
{
// From a ViewModel reference
ViewModel vm = riveWidget.File.GetViewModelByName("My View Model");
// Create blank
ViewModelInstance vmiBlank = vm.CreateInstance();
// Create default
ViewModelInstance vmiDefault = vm.CreateDefaultInstance();
// Create by index
for (int i = 0; i < vm.InstanceCount; i++)
{
ViewModelInstance vmiIndexed = vm.CreateInstanceAt(i);
}
// Create by name
ViewModelInstance vmiNamed = vm.CreateInstanceByName("My Instance");
}
}
```
### Binding
The created instance can then be assigned to a state machine or artboard. This establishes the bindings set up at edit time.
It is preferred to assign to a state machine, as this will automatically apply the instance to the artboard as well. Only assign to an artboard if you are not using a state machine, i.e. your file is static or uses linear animations.
> [!NOTE]
>
> The initial values of the instance are not applied to their bound elements until the state machine or artboard advances.
```csharp theme={null}
// Access the RiveWidget component
// Using the Unity Inspector
// 1. Select your RiveWidget in the Inspector
// 2. In the "Data" section, set the Data Binding Mode:
// - Auto Bind Default: Binds the default view model instance and any global view models
// - Auto Bind Selected: Uses a specific instance you select in the dropdown, plus any global view models
// - Manual: Requires you to set up binding in code
// Or programmatically if set to Manual or if using the low-level API
private void OnEnable()
{
riveWidget.OnWidgetStatusChanged += HandleWidgetStatusChanged;
}
private void OnDisable()
{
riveWidget.OnWidgetStatusChanged -= HandleWidgetStatusChanged;
}
private void HandleWidgetStatusChanged()
{
if (riveWidget.Status == WidgetStatus.Loaded)
{
ViewModel vm = riveWidget.Artboard.DefaultViewModel;
ViewModelInstance vmi = vm.CreateDefaultInstance();
// Applying to a state machine will automatically bind to its artboard
riveWidget.StateMachine.BindViewModelInstance(vmi);
}
}
```
`BindViewModelInstance(vmi)` binds `vmi` as the main instance. Empty [global view model](#global-view-models) slots are filled with default instances at the same time. To supply your own globals in that call, pass a dictionary of names to instances.
### Auto-Binding
Alternatively, you may prefer to use auto-binding. This will automatically bind the default view model of the artboard using the default instance to both the state machine and the artboard. The default view model is the one selected on the artboard in the editor dropdown. The default instance is the one marked "Default" in the editor.
> [tab] Component API (Recommended)
>
> *Rive Widget*\* provides both visual and programmatic ways to configure auto-binding. In the Inspector, you can easily set up binding through the Data Binding Mode dropdown:
>
> 
>
> To enable auto-binding programmatically, use the following APIs:
>
> ```csharp theme={null}
>
> // Before the widget is loaded:
>
> // Option 1: Auto bind the default instance (and default instances for any globals)
> riveWidget.BindingMode = DataBindingMode.AutoBindDefault;
>
> // Option 2: Auto bind a specific instance by name (and default instances for any globals)
> riveWidget.BindingMode = DataBindingMode.AutoBindSelected;
> riveWidget.ViewModelInstanceName = "My Instance";
>
> // Load the Rive file after setting the binding mode
> riveWidget.Load(riveFile, artboardName, stateMachineName);
>
> ...
> // Access the current instance that was auto-bound
> ViewModelInstance boundInstance = riveWidget.StateMachine.ViewModelInstance;
> ```
> [tab] Legacy API
>
> If you choose to use the low-level API to control the render loop, you'll need to manually set up data binding in your scripts.
>
> For reference, check this [RiveScreen example](https://github.com/rive-app/rive-unity/blob/main/examples/basic/Assets/GameRuntime/RiveScreen.cs) that demonstrates one way to implement auto binding in a custom render loop.
>
> > [!NOTE]
> >
> > Using the low-level API requires additional implementation effort and understanding of the Rive runtime. Unless you have a specific need to setup a custom render loop, we recommend using the Component API.
### Global View Models
A view model marked **global** in the editor is not owned by a single artboard. The file holds one named slot per global view model, so every artboard in that file can read the same properties. Use this for app-wide state such as a theme, locale, or settings. See [Global View Model Instances](/docs/editor/data-binding/view-models#global-view-model-instances) in the editor docs.
List the globals in a file with `File.GlobalViewModelNames`. The Rive asset inspector also labels them `(Global)`.
```csharp theme={null}
foreach (string name in riveWidget.File.GlobalViewModelNames)
{
Debug.Log($"Global: {name}");
}
```
How those slots get filled depends on the widget's **Data Binding Mode**:
* **Auto Bind Default** and **Auto Bind Selected** bind at load. They bind the main instance when the artboard has one, and they create a default instance for each empty global. Artboards with no main view model still Auto Bind when the file has globals.
* **Manual** binds nothing at load. You create the main instance and any globals, then bind them yourself.
> [!NOTE]
>
> **Auto Bind Selected** with an instance name that does not exist does not bind anything, including globals.
`GetGlobalViewModelInstance` returns `null` until something has bound, either Auto Bind at load or an explicit `BindViewModelInstance` call.
```csharp theme={null}
ViewModelInstance labels = riveWidget.StateMachine.GetGlobalViewModelInstance("Labels");
if (labels != null)
{
ViewModelInstanceStringProperty currency = labels.GetStringProperty("currency");
Debug.Log(currency.Value);
}
```
#### Overriding globals after Auto Bind
Auto Bind fills every global with a default instance. To replace some of those defaults at runtime, bind again and pass the widget's current main instance plus the globals you want to change. Globals you leave out of the dictionary keep the instance they already have.
```csharp theme={null}
riveWidget.BindingMode = DataBindingMode.AutoBindDefault;
riveWidget.Load(file);
var globals = new Dictionary
{
{ "Colors", file.GetViewModelByName("Colors").CreateDefaultInstance() },
{ "Labels", file.GetViewModelByName("Labels").CreateInstanceByName("US") },
};
riveWidget.StateMachine.BindViewModelInstance(
riveWidget.StateMachine.ViewModelInstance,
globals);
```
#### Binding manually
With **Manual**, nothing is bound after `Load`. Create the main instance and the globals, then bind them together.
```csharp theme={null}
riveWidget.BindingMode = DataBindingMode.Manual;
riveWidget.Load(file);
ViewModelInstance main = riveWidget.Artboard.DefaultViewModel.CreateDefaultInstance();
var globals = new Dictionary
{
{ "Colors", file.GetViewModelByName("Colors").CreateDefaultInstance() },
{ "Labels", file.GetViewModelByName("Labels").CreateInstanceByName("US") },
};
riveWidget.StateMachine.BindViewModelInstance(main, globals);
```
The two-argument overload returns `false` and leaves the state machine unchanged if the main instance is disposed, a dictionary key is not a global in the file, or a value is `null` or disposed. A `null` dictionary is treated as empty: omitted globals still receive defaults on the first bind.
#### Binding globals only
Pass `null` as the main instance to bind globals without supplying a main. Bind creates a default main when the artboard has a default view model, and still fills any global you leave out of the map.
```csharp theme={null}
riveWidget.StateMachine.BindViewModelInstance(
null,
new Dictionary
{
{ "Labels", file.GetViewModelByName("Labels").CreateInstanceByName("US") },
});
// Bind with no overrides. This is the same fill-defaults path Auto Bind uses:
riveWidget.StateMachine.BindViewModelInstance(null);
```
#### Sharing a global across widgets
Auto Bind creates a new default instance for each widget, so those defaults are not shared. To share a global without binding twice, set both widgets to **Manual**, then pass the same instance in each widget's first bind.
```csharp theme={null}
widgetA.BindingMode = DataBindingMode.Manual;
widgetB.BindingMode = DataBindingMode.Manual;
widgetA.Load(file);
widgetB.Load(file);
ViewModelInstance sharedLabels = file.GetViewModelByName("Labels").CreateInstanceByName("US");
var globals = new Dictionary { { "Labels", sharedLabels } };
ViewModelInstance mainA = widgetA.Artboard.DefaultViewModel.CreateDefaultInstance();
ViewModelInstance mainB = widgetB.Artboard.DefaultViewModel.CreateDefaultInstance();
widgetA.StateMachine.BindViewModelInstance(mainA, globals);
widgetB.StateMachine.BindViewModelInstance(mainB, globals);
// An edit through A is visible through B.
sharedLabels.GetStringProperty("currency").Value = "$";
```
> [!NOTE]
>
> The widgets do not necessarily have to be in `Manual` mode. You can bind a shared global after Auto Bind by passing each widget's current main instance plus the shared dictionary. `Manual` is shown here to avoid an unnecessary second bind.
# Properties
A property is a value that can be read, set, or observed on a view model instance. Properties can be of the following types:
| Type | Supported |
| - | - |
| Floating point numbers | ✅ |
| Booleans | ✅ |
| Triggers | ✅ |
| Strings | ✅ |
| Enumerations | ✅ |
| Colors | ✅ |
| Nested View Models | ✅ |
| Lists | ✅ |
| Images | ✅ |
| Artboards | ✅ |
For more information on version compatibility, see the [Feature Support](/docs/feature-support) page.
### Listing properties
Property descriptors can be inspected on a view model to discover at runtime which are available. These are not the mutable properties themselves though - once again those are on instances. These descriptors have a type and name.
```csharp theme={null}
var vm = riveWidget.File.GetViewModelByName("My View Model");
// A list of properties
var properties = vm.Properties;
foreach (var prop in properties)
{
Debug.Log($"Property: {prop.Name}, Type: {prop.Type}");
}
```
### Reading and writing properties
References to these properties can be retrieved by name or path.
Some properties are mutable and have getters, setters, and observer operations for their values. Getting or observing the value will retrieve the latest value set on that property's binding, as of the last state machine or artboard advance. Setting the value will update the value and all of its bound elements.
> [!NOTE]
>
> After setting a property's value, the changes will not apply to their bound elements until the state machine or artboard advances.
```csharp theme={null}
private void OnEnable()
{
riveWidget.OnWidgetStatusChanged += HandleWidgetStatusChanged;
}
private void OnDisable()
{
riveWidget.OnWidgetStatusChanged -= HandleWidgetStatusChanged;
}
private void HandleWidgetStatusChanged()
{
// Check if the widget is loaded before accessing the view model instance
if (riveWidget.Status == WidgetStatus.Loaded)
{
ViewModelInstance viewModelInstance = riveWidget.StateMachine.ViewModelInstance;
//==========================================================================
// STRING PROPERTIES
//==========================================================================
ViewModelInstanceStringProperty stringProperty = viewModelInstance.GetStringProperty("title");
Debug.Log($"String value: {stringProperty.Value}");
stringProperty.Value = "New Text";
//==========================================================================
// NUMBER PROPERTIES
//==========================================================================
ViewModelInstanceNumberProperty numberProperty = viewModelInstance.GetNumberProperty("count");
Debug.Log($"Number value: {numberProperty.Value}");
numberProperty.Value = 42.5f;
//==========================================================================
// BOOLEAN PROPERTIES
//==========================================================================
ViewModelInstanceBooleanProperty boolProperty = viewModelInstance.GetBooleanProperty("isActive");
Debug.Log($"Boolean value: {boolProperty.Value}");
boolProperty.Value = true;
//==========================================================================
// COLOR PROPERTIES
//==========================================================================
ViewModelInstanceColorProperty colorProperty = viewModelInstance.GetColorProperty("backgroundColor");
// Using Unity Color (float values 0-1)
Color currentColor = colorProperty.Value;
colorProperty.Value = new UnityEngine.Color(1, 0, 0, 1); // Red color
// Or using Color32 (byte values 0-255)
Color32 currentColor32 = colorProperty.Value32;
colorProperty.Value32 = new Color32(0, 255, 0, 255); // Green color
//==========================================================================
// ENUM PROPERTIES
//==========================================================================
ViewModelInstanceEnumProperty enumProperty = viewModelInstance.GetEnumProperty("category");
Debug.Log($"Enum current value: {enumProperty.Value}");
Debug.Log($"Enum available values: {string.Join(", ", enumProperty.EnumValues)}");
enumProperty.Value = "option_name";
//==========================================================================
// TRIGGER PROPERTIES
//==========================================================================
ViewModelInstanceTriggerProperty triggerProperty = viewModelInstance.GetTriggerProperty("onSubmit");
triggerProperty.Trigger(); // Fire the trigger
}
}
```
### Nested property paths
View models can have properties of type view model, allowing for arbitrary nesting. You can chain property calls on each instance starting from the root until you get to the property of interest. Alternatively, you can do this through a path parameter, which is similar to a URI in that it is a forward slash delimited list of property names ending in the name of the property of interest.
```csharp theme={null}
if (riveWidget.Status == WidgetStatus.Loaded)
{
var viewModelInstance = riveWidget.StateMachine.ViewModelInstance;
// Accessing nested view models using chaining
var nestedNumberByChain = viewModelInstance
.GetViewModelInstanceProperty("My Nested View Model")
.GetViewModelInstanceProperty("My Second Nested VM")
.GetNumberProperty("My Nested Number");
// Accessing nested properties using path notation
var nestedNumberByPath = viewModelInstance
.GetNumberProperty("My Nested View Model/My Second Nested VM/My Nested Number");
}
```
### Observability
You can observe changes over time to property values, either by using listeners or a platform equivalent method. Once observed, you will be notified when the property changes are applied by a state machine advance, whether that is a new value that has been explicitly set or if the value was updated as a result of a binding.
```csharp theme={null}
private ViewModelInstanceNumberProperty numberProperty;
private ViewModelInstanceStringProperty stringProperty;
private ViewModelInstanceBooleanProperty boolProperty;
private ViewModelInstanceColorProperty colorProperty;
private ViewModelInstanceEnumProperty enumProperty;
private ViewModelInstanceTriggerProperty triggerProperty;
private void OnEnable()
{
riveWidget.OnWidgetStatusChanged += HandleWidgetStatusChanged;
}
private void OnDisable()
{
riveWidget.OnWidgetStatusChanged -= HandleWidgetStatusChanged;
}
private void HandleWidgetStatusChanged()
{
if (riveWidget.Status == WidgetStatus.Loaded)
{
ViewModelInstance viewModelInstance = riveWidget.StateMachine.ViewModelInstance;
// Add listeners to properties
numberProperty = viewModelInstance.GetNumberProperty("count");
numberProperty.OnValueChanged += OnNumberPropertyChanged;
stringProperty = viewModelInstance.GetStringProperty("title");
stringProperty.OnValueChanged += OnStringPropertyChanged;
boolProperty = viewModelInstance.GetBooleanProperty("isActive");
boolProperty.OnValueChanged += OnBoolPropertyChanged;
colorProperty = viewModelInstance.GetColorProperty("backgroundColor");
colorProperty.OnValueChanged += OnColorPropertyChanged;
enumProperty = viewModelInstance.GetEnumProperty("category");
enumProperty.OnValueChanged += OnEnumPropertyChanged;
triggerProperty = viewModelInstance.GetTriggerProperty("onSubmit");
triggerProperty.OnTriggered += OnTriggerPropertyFired;
}
}
private void OnNumberPropertyChanged(float newValue)
{
Debug.Log($"Number changed to: {newValue}");
}
private void OnStringPropertyChanged(string newValue)
{
Debug.Log($"String changed to: {newValue}");
}
private void OnBoolPropertyChanged(bool newValue)
{
Debug.Log($"Boolean changed to: {newValue}");
}
private void OnColorPropertyChanged(UnityEngine.Color newValue)
{
Debug.Log($"Color changed to: {ColorUtility.ToHtmlStringRGBA(newValue)}");
}
private void OnEnumPropertyChanged(string newValue)
{
Debug.Log($"Enum changed to: {newValue}");
}
private void OnTriggerPropertyFired()
{
Debug.Log("Trigger fired!");
}
private void OnDestroy()
{
// You should remove listeners when no longer needed,
numberProperty.OnValueChanged -= OnNumberPropertyChanged;
stringProperty.OnValueChanged -= OnStringPropertyChanged;
boolProperty.OnValueChanged -= OnBoolPropertyChanged;
colorProperty.OnValueChanged -= OnColorPropertyChanged;
enumProperty.OnValueChanged -= OnEnumPropertyChanged;
triggerProperty.OnTriggered -= OnTriggerPropertyFired;
}
```
### Images
Image properties let you set and replace raster images at runtime, with each instance of the image managed independently. For example, you could build an avatar creator and dynamically update features — like swapping out a hat — by setting a view model's image property.
```csharp theme={null}
[SerializeField] private ImageOutOfBandAsset m_lightImageAsset;
[SerializeField] private ImageOutOfBandAsset m_darkImageAsset;
private ViewModelInstanceImageProperty imageProperty;
private bool isDarkMode = false;
private void OnEnable()
{
riveWidget.OnWidgetStatusChanged += HandleWidgetStatusChanged;
}
private void OnDisable()
{
riveWidget.OnWidgetStatusChanged -= HandleWidgetStatusChanged;
}
private void HandleWidgetStatusChanged()
{
if (riveWidget.Status == WidgetStatus.Loaded)
{
m_lightImageAsset.Load();
m_darkImageAsset.Load();
ViewModelInstance viewModelInstance = riveWidget.StateMachine.ViewModelInstance;
// Get the image property by name
imageProperty = viewModelInstance.GetImageProperty("profileImage");
// or alternatively:
// imageProperty = viewModelInstance.GetProperty("profileImage");
// Set up change callback
imageProperty.OnValueChanged += OnImageChanged;
// Set initial image (light mode)
imageProperty.Value = m_lightImageAsset;
}
}
private void OnImageChanged()
{
Debug.Log("Image updated!");
}
// Example method to toggle between light and dark mode images
public void ToggleTheme()
{
if (imageProperty != null)
{
isDarkMode = !isDarkMode;
imageProperty.Value = isDarkMode ? m_darkImageAsset : m_lightImageAsset;
}
}
// Example method to clear the image
public void ClearImage()
{
if (imageProperty != null)
{
imageProperty.Value = null;
}
}
private void OnDestroy()
{
m_lightImageAsset.Unload();
m_darkImageAsset.Unload();
// Remove the event listener
if (imageProperty != null)
{
imageProperty.OnValueChanged -= OnImageChanged;
}
}
```
For a demo of image data binding in Unity, see the **Image Data Binding** scene in the [Rive Unity Examples repository](https://github.com/rive-app/rive-unity-examples).
### Fonts
Font properties let you swap the typeface used by bound text at runtime. Decode font bytes and assign the result to the property's value.
Assign a loaded `FontOutOfBandAsset` to the property. Call `Load()` before you set `Value`, and call `Unload()` when you no longer need the font. Unlike [runtime asset swapping](/docs/game-runtimes/unity/runtime-asset-swapping), this only changes text bound to that font property, so different parts of the file can use different fonts.
`Value` is set-only.
```csharp theme={null}
[SerializeField] private FontOutOfBandAsset m_headingFont;
private ViewModelInstanceFontProperty fontProperty;
private void OnEnable()
{
riveWidget.OnWidgetStatusChanged += HandleWidgetStatusChanged;
}
private void OnDisable()
{
riveWidget.OnWidgetStatusChanged -= HandleWidgetStatusChanged;
}
private void HandleWidgetStatusChanged()
{
if (riveWidget.Status == WidgetStatus.Loaded)
{
m_headingFont.Load();
ViewModelInstance viewModelInstance = riveWidget.StateMachine.ViewModelInstance;
fontProperty = viewModelInstance.GetFontProperty("headingFont");
// alternatively:
// fontProperty = viewModelInstance.GetProperty("headingFont");
fontProperty.OnValueChanged += OnFontChanged;
fontProperty.Value = m_headingFont;
}
}
private void OnFontChanged()
{
Debug.Log("Font updated");
}
private void OnDestroy()
{
m_headingFont.Unload();
if (fontProperty != null)
{
fontProperty.OnValueChanged -= OnFontChanged;
}
}
```
> [!NOTE]
>
> Assigning an unloaded font logs a warning and does not update the property. To create a font at runtime from raw bytes, use `OutOfBandAsset.Create(bytes)` as described in [Runtime Asset Swapping](/docs/game-runtimes/unity/runtime-asset-swapping#creating-out-of-band-assets-dynamically).
### Render Textures
> [!WARNING]
>
> **Experimental Feature**
>
> This feature is not enabled out of the box. Add `RIVE_USING_EXPERIMENTAL` under **Project Settings → Player → Scripting Define Symbols** to use it.
>
> These APIs are still in development and may change before they become stable.
>
> Unity applies scripting defines per platform. If you ship to multiple targets (Standalone, iOS, Android, and so on), add the define on each platform tab where you need this feature.
The image examples above use `ImageOutOfBandAsset` to bind static raster images loaded from disk. Use `RenderTextureImageSource` when the image comes from a live Unity `RenderTexture` instead, such as `VideoPlayer` output, a camera render target, or custom GPU content you change each frame.
`RenderTextureImageSource` wraps the texture as a native Rive image and binds it to a view model image property through `SetFromRenderTextureImageSource`. Once bound, the runtime keeps the visuals up to date for you.
The example below binds a `VideoPlayer` render target to a view model image property named `"video"`. Wait until the Rive widget is loaded before binding, then call `SetFromRenderTextureImageSource` once. The runtime handles per-frame updates after that.
```csharp theme={null}
#if RIVE_USING_EXPERIMENTAL
using System.Collections;
using UnityEngine;
using UnityEngine.Video;
using Rive;
using Rive.Components;
public class VideoImageBinding : MonoBehaviour
{
[SerializeField] private RiveWidget riveWidget;
[SerializeField] private RenderTexture videoTexture;
[SerializeField] private string viewModelImagePath = "video";
[SerializeField] private VideoPlayer videoPlayer;
[Tooltip("How the video is adapted before Rive samples it.")]
[SerializeField]
private RenderTextureImageSource.TextureProcessingMode processingMode =
RenderTextureImageSource.TextureProcessingMode.Auto;
private RenderTextureImageSource renderTextureSource;
private void Start()
{
if (videoTexture == null || riveWidget == null || videoPlayer == null)
{
Debug.LogWarning("Assign videoTexture, riveWidget, and videoPlayer in the Inspector.");
return;
}
videoPlayer.renderMode = VideoRenderMode.RenderTexture;
videoPlayer.targetTexture = videoTexture;
videoPlayer.prepareCompleted += OnVideoPrepared;
videoPlayer.Prepare();
}
private void OnVideoPrepared(VideoPlayer source)
{
StartCoroutine(BindAndPlay());
}
private IEnumerator BindAndPlay()
{
while (riveWidget.Status != WidgetStatus.Loaded ||
riveWidget.StateMachine == null)
{
yield return null;
}
ViewModelInstance viewModelInstance = riveWidget.StateMachine.ViewModelInstance;
if (viewModelInstance == null)
{
Debug.LogWarning("No ViewModelInstance on the widget.");
yield break;
}
ViewModelInstanceImageProperty imageProperty =
viewModelInstance.GetImageProperty(viewModelImagePath);
if (imageProperty == null)
{
Debug.LogWarning($"Image property '{viewModelImagePath}' not found.");
yield break;
}
renderTextureSource = new RenderTextureImageSource(videoTexture, processingMode);
imageProperty.SetFromRenderTextureImageSource(renderTextureSource);
videoPlayer.Play();
}
private void OnDestroy()
{
if (videoPlayer != null)
{
videoPlayer.prepareCompleted -= OnVideoPrepared;
videoPlayer.Stop();
videoPlayer.targetTexture = null;
}
renderTextureSource?.Dispose();
}
}
#endif
```
#### When to use it
| Approach | Use when |
| - | - |
| `ImageOutOfBandAsset` | You have a static image file (PNG, JPG, WebP, etc.) loaded at runtime |
| `RenderTextureImageSource` | You already have a Unity `RenderTexture` whose contents change over time |
Both APIs bind to the same view model image property type. A property can only be driven by one source at a time. Assigning an `ImageOutOfBandAsset` through `Value` automatically unbinds an active render-texture source, and vice versa.
#### Requirements and limitations
The source must be a stable, user-allocated 2D `RenderTexture`. Do not use transient RenderGraph resources. Their backing memory can be reused and produce stale samples or crashes.
Supported source formats:
* Single-sample, non-MSAA
* 2D only (not cube, array, or 3D)
* Created and kept alive for as long as the binding is active
Supported graphics backends:
| Backend | Supported |
| - | - |
| Metal | Yes |
| Direct3D 11 | Yes |
| Direct3D 12 | Yes |
| Vulkan | Yes |
| OpenGL / WebGL | No |
On unsupported backends, binding safe-fails: the property stays empty and an error is logged.
Rive composites through an 8-bit internal render target, so HDR source values above 1.0 are clamped at the Rive layer.
#### Texture processing
Unity backends differ in whether render texture texels are stored top-down or bottom-up. In Linear color space projects, Unity may also hand Rive gamma-encoded values that get decoded twice when the panel composites.
To avoid requiring every project to handle these fixes manually, the default `TextureProcessingMode.Auto` blits through an owned intermediate render texture and applies a flip and/or gamma re-encode only when the active backend or project settings actually need it.
| Mode | Behavior |
| - | - |
| `Auto` | Apply orientation and color fixes when needed. This is the default processing mode. |
| `Orientation` | Flip upside-down textures on backends that store texels top-down. Leave color alone. |
| `Color` | Re-encode to gamma in Linear projects so colors composite correctly. Leave orientation alone. |
| `None` | Bind the source render texture directly with no intermediate blit. Use this when your texture is already correctly oriented and encoded. |
```csharp theme={null}
// Default: let the runtime decide what processing is needed
var source = new RenderTextureImageSource(renderTexture);
// Opt out when you already produce a correctly oriented, correctly encoded texture
var directSource = new RenderTextureImageSource(
renderTexture,
RenderTextureImageSource.TextureProcessingMode.None);
```
#### Refresh behavior
`RenderTextureImageSource` controls how often the bound image property is updated from the source texture.
| Mode | Behavior |
| - | - |
| `PerFrame` | Rebuild and re-push every frame. This is the default refresh mode. Use for live sources such as video or camera output. |
| `Manual` | Update only when you call `Refresh()`. Use for snapshots, baked textures, or content that isn't updated very often. |
```csharp theme={null}
// Live source (default)
var liveSource = new RenderTextureImageSource(
renderTexture,
refreshMode: RenderTextureImageSource.RefreshMode.PerFrame);
// Snapshot / on-demand source
var snapshotSource = new RenderTextureImageSource(
renderTexture,
refreshMode: RenderTextureImageSource.RefreshMode.Manual);
// After writing new content into the render texture:
snapshotSource.Refresh();
```
#### Clearing and switching images
To clear a render-texture-backed image:
```csharp theme={null}
imageProperty.SetFromRenderTextureImageSource(null);
```
To switch back to a regular image asset:
```csharp theme={null}
imageAsset.Load();
imageProperty.Value = imageAsset;
```
Assigning `Value` automatically detaches any active `RenderTextureImageSource` binding on that property.
#### Lifecycle and teardown
While a `RenderTextureImageSource` is bound to at least one image property, the runtime keeps it alive and updating.
When you are done with a source, call `Dispose()` to stop updates and release any intermediate GPU resources owned by Rive.
##### Recommended teardown order
`RenderTextureImageSource` does not own your `RenderTexture`. When shutting down, use this order:
1. **Stop producers.** Stop or disconnect anything still writing into the texture (`VideoPlayer`, camera, custom blit loop, etc.).
2. **Unbind and dispose the image source.** Call `Dispose()` on the `RenderTextureImageSource`, or call `SetFromRenderTextureImageSource(null)` and then `Dispose()`.
3. **Release your render texture (if you created it).** If you allocated the `RenderTexture` at runtime, call `Release()` and then `Destroy()` on it.
```csharp theme={null}
private void OnDestroy()
{
// 1. Stop writing into the texture
if (videoPlayer != null)
{
videoPlayer.Stop();
videoPlayer.targetTexture = null;
}
// 2. Unbind and dispose the Rive image source
renderTextureSource?.Dispose();
renderTextureSource = null;
// 3. Only if you created the RenderTexture at runtime
if (ownsRenderTexture && renderTexture != null)
{
renderTexture.Release();
Destroy(renderTexture);
}
}
```
> [!NOTE]
>
> If your `RenderTexture` is a project asset assigned in the Inspector (as in the video example above), you only need steps 1 and 2. Do not call `Destroy()` on shared or asset-backed render textures.
Destroying or releasing the source texture before step 2 is tolerated (the bound property clears on the next tick), but disposing the image source first is the safer path. It avoids Rive attempting to wrap a texture that is already being released.
### Lists
List properties let you manage a dynamic set of view model instances at runtime. For example, you can build a to-do app where users can add and remove tasks in a scrollable Layout.
See the [Editor section](/docs/editor/data-binding/lists) on creating data bound lists.
A single list property can include different view model types, with each view model tied to its own Component, making it easy to populate a list with a variety of Component instances.
With list properties, you can:
* Add a new view model instance (optionally at an index)
* Remove an existing view model instance (optionally by index)
* Swap two view model instances by index
* Get the size of a list
For more information on list properties, see the [Data Binding List Property](/docs/editor/data-binding/lists#view-model-list-property) editor documentation.
```csharp theme={null}
private ViewModelInstanceListProperty listProperty;
private void OnEnable()
{
riveWidget.OnWidgetStatusChanged += HandleWidgetStatusChanged;
}
private void OnDisable()
{
riveWidget.OnWidgetStatusChanged -= HandleWidgetStatusChanged;
}
private void HandleWidgetStatusChanged()
{
if (riveWidget.Status == WidgetStatus.Loaded)
{
ViewModelInstance viewModelInstance = riveWidget.StateMachine.ViewModelInstance;
// Get the list property by name
listProperty = viewModelInstance.GetListProperty("todos");
// or alternatively:
// var listProperty = viewModelInstance.GetProperty("todos");
Debug.Log($"List count: {listProperty.Count}");
// Set up change callback
listProperty.OnChanged += OnListChanged;
// Get the view model for creating new instances
var todoItemVM = riveWidget.File.GetViewModelByName("TodoItem");
// Create a blank instance from the view model
var newTodo = todoItemVM.CreateInstance();
newTodo.GetStringProperty("description").Value = "Buy groceries";
// Add the newly created instance to the list
listProperty.Add(newTodo);
// Insert an instance at a specific index
var anotherTodo = todoItemVM.CreateInstance();
listProperty.Insert(anotherTodo, 0); // Insert at beginning
// Access items by index
for (int i = 0; i < listProperty.Count; i++)
{
var item = listProperty.GetInstanceAt(i);
Debug.Log($"Item {i}: {item}");
}
// Remove a specific instance from the list
listProperty.Remove(newTodo);
// Remove instance at index
listProperty.RemoveAt(0);
// Swap two instances in the list at index 0 and 1
if (listProperty.Count > 1)
{
listProperty.Swap(0, 1);
}
}
}
private void OnListChanged()
{
Debug.Log("List updated!");
}
private void OnDestroy()
{
if (listProperty != null)
{
listProperty.OnChanged -= OnListChanged;
}
}
```
### Artboards
Artboard properties allows you to swap out entire components at runtime. This is useful for creating modular components that can be reused across different designs or applications, for example:
* Creating a skinning system that supports a large number of variations, such as a character creator where you can swap out different body parts, clothing, and accessories.
* Creating a complex scene that is a composition of various artboards loaded from various different Rive files (drawn to a single canvas/texture/widget).
* Reducing the size (complexity) of a single Rive file by breaking it up into smaller components that can be loaded on demand and swapped in and out as needed.
Artboard properties work with the `BindableArtboard` class, which is different from the regular `Artboard` class in the package.
`BindableArtboard` is a runtime wrapper for interacting with artboards through data binding. These instances reference existing artboards in your file, so no additional setup is required in the Rive Editor.
```csharp theme={null}
[SerializeField] private Asset m_externalRiveAsset;
private ViewModelInstanceArtboardProperty artboardProperty;
private File externalFile;
private void OnEnable()
{
riveWidget.OnWidgetStatusChanged += HandleWidgetStatusChanged;
}
private void OnDisable()
{
riveWidget.OnWidgetStatusChanged -= HandleWidgetStatusChanged;
}
private void HandleWidgetStatusChanged()
{
if (riveWidget.Status == WidgetStatus.Loaded)
{
ViewModelInstance viewModelInstance = riveWidget.StateMachine.ViewModelInstance;
// Get the artboard property by name
artboardProperty = viewModelInstance.GetArtboardProperty("artboard_1");
// or alternatively:
// artboardProperty = viewModelInstance.GetProperty("artboard_1");
// Set up change callback
artboardProperty.OnValueChanged += OnArtboardChanged;
// Set artboard from same file.
var blueArtboard = riveWidget.File.BindableArtboard("ArtboardBlue");
artboardProperty.Value = blueArtboard;
// Load external file if needed
if (m_externalRiveAsset != null)
{
externalFile = File.Load(m_externalRiveAsset);
}
}
}
private void OnArtboardChanged()
{
Debug.Log("Artboard changed");
}
// Example method to assign a different artboard from the same file
public void SwitchToRedArtboard()
{
if (artboardProperty != null)
{
var redArtboard = riveWidget.File.BindableArtboard("ArtboardRed");
artboardProperty.Value = redArtboard;
}
}
// Example method to assign an artboard from a different file
// This is useful for creating modular components that can be reused across different Rive files.
public void SwitchToExternalArtboard()
{
if (artboardProperty != null && externalFile != null)
{
var externalArtboard = externalFile.BindableArtboard("SomeArtboard");
artboardProperty.Value = externalArtboard;
}
}
private void OnDestroy()
{
// Clean up external file
externalFile?.Dispose();
// Remove the event listener
if (artboardProperty != null)
{
artboardProperty.OnValueChanged -= OnArtboardChanged;
}
}
```
### Using custom View Model instances with bindable artboards
You can link a custom `ViewModelInstance` to a bindable artboard, giving you control over the data being used by that artboard.
To create a bindable artboard with a custom view model instance, use the overload on the `File` instance that contains the artboard:
```csharp theme={null}
var file = riveWidget.File;
var viewModelInstance = file.GetViewModelByName("CharacterData").CreateInstance();
var bindableArtboard = file.BindableArtboard("FeaturedCharacterCard", viewModelInstance);
```
**Example: Featured Content Slot**
Imagine you have a home screen with a single "featured" content area that can display different types of promotions. Each content type uses a **different artboard with its own unique data structure**. Your main UI file contains the home screen layout with a featured content slot that you can populate dynamically:
```csharp theme={null}
private ViewModelInstanceArtboardProperty featuredContentSlot;
private ViewModelInstance characterData;
private ViewModelInstance eventData;
private ViewModelInstance offerData;
private BindableArtboard featuredCharacter;
private BindableArtboard limitedEvent;
private BindableArtboard specialOffer;
private void HandleWidgetStatusChanged()
{
if (riveWidget.Status == WidgetStatus.Loaded)
{
ViewModelInstance viewModelInstance = riveWidget.StateMachine.ViewModelInstance;
// Get the featured content slot from your main UI
featuredContentSlot = viewModelInstance.GetArtboardProperty("featuredContentSlot");
// Featured Character has its own unique data structure
var characterViewModel = riveWidget.File.GetViewModelByName("CharacterData");
characterData = characterViewModel.CreateInstance();
var charName = characterData.GetStringProperty("name");
var charClass = characterData.GetStringProperty("class");
var attackPower = characterData.GetNumberProperty("attackPower");
var specialAbility = characterData.GetStringProperty("specialAbility");
var isUnlocked = characterData.GetBoolProperty("unlocked");
charName.Value = "Shadowblade";
charClass.Value = "Assassin";
attackPower.Value = 92;
specialAbility.Value = "Phantom Strike";
isUnlocked.Value = false;
// Limited-Time Event has its own unique data structure
var eventViewModel = riveWidget.File.GetViewModelByName("EventData");
eventData = eventViewModel.CreateInstance();
var eventTitle = eventData.GetStringProperty("title");
var eventDescription = eventData.GetStringProperty("description");
var hoursRemaining = eventData.GetNumberProperty("hoursRemaining");
var participantCount = eventData.GetNumberProperty("participants");
var isActive = eventData.GetBoolProperty("active");
eventTitle.Value = "Dragon Raid Weekend";
eventDescription.Value = "Team up to defeat the ancient dragon";
hoursRemaining.Value = 36;
participantCount.Value = 1247;
isActive.Value = true;
// Special Offer has its own unique data structure
var offerViewModel = riveWidget.File.GetViewModelByName("OfferData");
offerData = offerViewModel.CreateInstance();
var offerName = offerData.GetStringProperty("itemName");
var originalPrice = offerData.GetNumberProperty("originalPrice");
var discountPercent = offerData.GetNumberProperty("discount");
var currency = offerData.GetStringProperty("currencyType");
var timeLeftHours = offerData.GetNumberProperty("expiresInHours");
offerName.Value = "Legendary Weapon Pack";
originalPrice.Value = 2999;
discountPercent.Value = 50;
currency.Value = "Gems";
timeLeftHours.Value = 12;
// Create bindable artboards. Each uses a DIFFERENT artboard with unique design
featuredCharacter = riveWidget.File.BindableArtboard("FeaturedCharacterCard", characterData);
limitedEvent = riveWidget.File.BindableArtboard("EventBanner", eventData);
specialOffer = riveWidget.File.BindableArtboard("OfferCard", offerData);
// Start by showing the featured character
featuredContentSlot.Value = featuredCharacter;
}
}
// Switch to showing the limited-time event
public void ShowLimitedEvent()
{
if (featuredContentSlot != null && limitedEvent != null)
{
featuredContentSlot.Value = limitedEvent;
}
}
// Switch to showing the special offer
public void ShowSpecialOffer()
{
if (featuredContentSlot != null && specialOffer != null)
{
featuredContentSlot.Value = specialOffer;
}
}
// Update event countdown timer
public void UpdateEventTimer(float deltaTime)
{
if (eventData != null)
{
var hoursRemaining = eventData.GetNumberProperty("hoursRemaining");
hoursRemaining.Value -= (deltaTime / 3600f); // Convert seconds to hours
}
}
private void OnDestroy()
{
// Clean up view model instances
characterData?.Dispose();
eventData?.Dispose();
offerData?.Dispose();
// Clean up bindable artboards
featuredCharacter?.Dispose();
limitedEvent?.Dispose();
specialOffer?.Dispose();
// Remove event listeners if any were added
if (featuredContentSlot != null)
{
featuredContentSlot.OnValueChanged -= OnArtboardChanged;
}
}
```
### Enums
Enums properties come in two flavors: system and user-defined. In practice, you will not need to worry about the distinction, but just be aware that system enums are available in any Rive file that binds to an editor-defined enum set, representing options from the editor's dropdowns, where user-defined enums are those defined by a designer in the editor.
Enums are string typed. The Rive file contains a list of enums. Each enum in turn has a name and a list of strings.
```csharp theme={null}
var viewModelInstance = riveWidget.StateMachine.ViewModelInstance;
// Accessing enums from the file
var enums = riveWidget.File.ViewModelEnums;
foreach (var enumType in enums)
{
Debug.Log($"Enum: {enumType.Name}");
foreach (var value in enumType.Values)
{
Debug.Log($" - Value: {value}");
}
}
...
// Using enum properties
var enumProperty = viewModelInstance.GetEnumProperty("category");
Debug.Log($"Current value: {enumProperty.Value}");
Debug.Log($"Available values: {string.Join(", ", enumProperty.EnumValues)}");
enumProperty.Value = enumProperty.EnumValues[0]; // Set to first value
```
# FAQ
Source: https://rive.app/docs/game-runtimes/unity/faq
Common questions for the Unity runtime.
## Does Rive support Unity's Sprite Renderer?
Rive renders to a **Render Texture** in Unity. Unity's **Sprite Renderer** doesn't handle Render Textures particularly well out of the box, so using Rive directly as a sprite usually requires a workaround.
In general, we recommend building your visuals in Rive and driving behavior with **data binding**, rather than trying to treat Rive files as a drop-in replacement for individual sprites that are then assembled in Unity.
If you absolutely need a 2D-style workflow of rendering Rive files as individual objects in Unity, the recommended workaround is to render Rive onto a **Quad** (or other mesh) using the **Rive Texture Renderer**, rather than trying to display a Render Texture through a Sprite Renderer. Note that there are [performance considerations](/docs/game-runtimes/unity/best-practices) to keep in mind when using this approach.
> [!NOTE]
>
> If you choose to use a Sprite Renderer workaround (especially custom shader approaches), we can't provide support for debugging or maintaining that custom rendering path as it is not officially supported.
## Does Rive support UI Toolkit?
Not yet, but we're working on it.
Today, the recommended approach is to use **uGUI** (via the **Rive Canvas Renderer**) or render Rive to a mesh.
## Why isn't my Rive graphic displaying?
A few common gotchas:
* Your **Rive Widget** needs to be under a **Rive Panel** to be rendered.
* A camera needs to be present in the scene.
See: [Unity components](/docs/game-runtimes/unity/components).
## Unity crashes when upgrading the package. What should I do?
If Unity crashes while upgrading the package, close the Unity Editor, update the version in `Packages/manifest.json`, and then reopen the project.
See: [Getting Started](/docs/game-runtimes/unity/getting-started).
## How do I report a bug or crash?
If you hit a crash or unexpected behavior, please file an issue in the [rive-unity GitHub repo](https://github.com/rive-app/rive-unity/issues).
To help us reproduce and diagnose the issue:
* In Unity, run **Tools → Rive → Copy Support Info** and paste the output into the issue.
* Include your **Editor.log**.
See: [Bug reports](/docs/game-runtimes/unity/unity#bug-reports).
# Fundamentals
Source: https://rive.app/docs/game-runtimes/unity/fundamentals
## Adding Rive assets
To add a `.riv` file to a Unity project, simply drag it into the Project Window. Once dropped, a **Rive Asset** will be automatically created.
Now you can display the Rive Asset within a **Rive Panel** and **Rive Widget**.
## File
A `Rive.File` contains Artboards, StateMachines, and Animations.
> [!NOTE]
>
> If you're working with the Rive Panel and Rive Widgets components, the Rive Widget will automatically handle loading the underlying Rive File from the assigned Asset.\
> You only need to use this class directly if you want control of the lifecycle of the Rive File, or if you need to load the file from an external source like a CDN.
The `Rive.File` class also provides several methods to load Rive content into Unity:
> [!NOTE]
>
> If the file is already in memory, a cached version will be returned to improve performance and avoid redundant loading.
#### 1. From a Rive asset (.riv file)
You can load a `Rive.File` from an imported `.riv` asset in the inspector:
```csharp theme={null}
public Rive.Asset asset; // pass in .riv asset in the inspector
private Rive.File m_file;
...
private void Start()
{
if (asset != null)
{
m_file = Rive.File.Load(asset);
}
}
```
#### 2. From a Unity TextAsset
You can load a `Rive.File` from a Unity `TextAsset`. This is useful if you have the bytes bundled as a `TextAsset` in the Unity project.
```csharp theme={null}
public TextAsset riveTextAsset; // assign in the inspector
private Rive.File m_file;
...
private void Start()
{
if (riveTextAsset != null)
{
m_file = Rive.File.Load(riveTextAsset);
}
}
```
#### 3. From a byte array
If you have the raw bytes of a `.riv` file, you can load it directly from a byte array. This method provides flexibility if you're loading the file data from a custom source or dynamically (e.g. from a CDN-stored file):
```csharp theme={null}
private byte[] riveFileBytes; // Your byte array, loaded from remote storage, for example.
private Rive.File m_file;
...
private void Start()
{
if (riveFileBytes != null)
{
m_file = Rive.File.Load(riveFileBytes, "myRiveFileName");
}
}
```
## Artboards
[Artboards](/docs/editor/fundamentals/artboards) contain [State Machines](/docs/editor/state-machine/state-machine) and Animations.
> [tab] Components
>
> Using a **Rive Widget** component, you can select from a list of available artboards within a given **Rive File**.
>
> 
> [tab] Legacy API
>
> > [!WARNING]
> >
> > Using the low-level API is no longer recommended. Please use the [Component API](/docs/game-runtimes/unity/components) instead for ease of use and maintainability. This content is provided for legacy support only.
>
> Artboards are instantiated from a `Rive.File` instance:
>
> ```java theme={null}
> private Artboard m_artboard;
>
> ...
>
> m_artboard = m_file.Artboard(0); // by index
> m_artboard = m_file.Artboard("Arboard 1"); // by name
> ```
## State Machines
For more information, see [State Machines](/docs/game-runtimes/unity/state-machines).
> [tab] Components
>
> Using a **Rive Widget** component, you can select from a list of available state machines within a given Artboard.
>
> 
> [tab] Legacy API
>
> > [!WARNING]
> >
> > Using the low-level API is no longer recommended. Please use the [Component API](/docs/game-runtimes/unity/components) instead for ease of use and maintainability. This content is provided for legacy support only.
>
> State Machines are instantiated from an Artboard instance:
>
> ```csharp theme={null}
> private StateMachine m_stateMachine;
>
> ...
>
> m_stateMachine = m_artboard?.StateMachine(); // default state machine
> m_stateMachine = m_artboard?.StateMachine(0); // state machine at index
> m_stateMachine = m_artboard?.StateMachine("Name"); // state machine with name
> ```
>
> They also control advancing (playing) an animation:
>
> ```csharp theme={null}
> private void Update()
> {
> m_stateMachine?.Advance(Time.deltaTime);
> }
> ```
## Rendering
In Unity, Rive renders to a [RenderTexture](https://docs.unity3d.com/ScriptReference/RenderTexture.html) that you can display in your Scene by attaching to a [Material](https://docs.unity3d.com/ScriptReference/Material.html) or anywhere else you would use a Render Texture within your project.
> [tab] Components
>
> The **Rive Panel** automatically renders its **Rive Widgets** to a Render Texture.
>
> Using the **Rive Canvas Renderer**, you can display a **Rive Panel** within a uGUI Canvas.
>
> To display a **Rive Panel** on a GameObject's mesh, use the **Rive Texture Renderer.**
> [tab] Legacy API
>
> > [!WARNING]
> >
> > Using the low-level API is no longer recommended. Please use the [Component API](/docs/game-runtimes/unity/components) instead for ease of use and maintainability. This content is provided for legacy support only.
>
> Layout and draw commands are managed through the `Rive.Renderer`.
>
> For a more complex example drawing a texture directly to a camera, see the **getting-started** project in the [examples repository](https://github.com/rive-app/rive-unity-examples).
>
> The following is a basic example script behaviour to render a given Rive asset to the provided `renderTexture`. The animation is played by calling `.Advance()` on the State Machine.
>
> See [State Machines](/docs/game-runtimes/unity/state-machines) for more general information on playing state machines at runtime.
>
> ```csharp theme={null}
> using System.Collections;
> using UnityEngine;
> using UnityEngine.Rendering;
> using UnityEditor;
> using Rive;
>
> using LoadAction = UnityEngine.Rendering.RenderBufferLoadAction;
> using StoreAction = UnityEngine.Rendering.RenderBufferStoreAction;
>
> public class RiveTexture : MonoBehaviour
> {
> public Rive.Asset asset;
> public RenderTexture renderTexture;
> public Fit fit = Fit.contain;
> public Alignment alignment = Alignment.Center;
>
> private Rive.RenderQueue m_renderQueue;
> private Rive.Renderer m_riveRenderer;
> private CommandBuffer m_commandBuffer;
>
> private Rive.File m_file;
> private Artboard m_artboard;
> private StateMachine m_stateMachine;
>
> private Camera m_camera;
>
> private void Start()
> {
> // If on D3d11, this is required
> renderTexture.enableRandomWrite = true;
> m_renderQueue = new Rive.RenderQueue(renderTexture);
> m_riveRenderer = m_renderQueue.Renderer();
> if (asset != null)
> {
> m_file = Rive.File.Load(asset);
> m_artboard = m_file.Artboard(0);
> m_stateMachine = m_artboard?.StateMachine();
> }
>
> if (m_artboard != null && renderTexture != null)
> {
> m_riveRenderer.Align(fit, alignment, m_artboard);
> m_riveRenderer.Draw(m_artboard);
>
> m_commandBuffer = m_riveRenderer.ToCommandBuffer();
> m_commandBuffer.SetRenderTarget(renderTexture);
> m_commandBuffer.ClearRenderTarget(true, true, UnityEngine.Color.clear, 0.0f);
> m_riveRenderer.AddToCommandBuffer(m_commandBuffer);
> m_camera = Camera.main;
> if (m_camera != null)
> {
> Camera.main.AddCommandBuffer(CameraEvent.AfterEverything, m_commandBuffer);
> }
> }
> }
>
> private void Update()
> {
> if (m_stateMachine != null)
> {
> m_stateMachine.Advance(Time.deltaTime);
> }
> }
>
> private void OnDisable()
> {
> if (m_camera != null && m_commandBuffer != null)
> {
> m_camera.RemoveCommandBuffer(CameraEvent.AfterEverything, m_commandBuffer);
> }
> }
> }
> ```
>
> 1. Create a Unity [RenderTexture](https://docs.unity.cn/ru/2020.1/Manual/class-RenderTexture.html) and [Material](https://docs.unity3d.com/2019.3/Documentation/Manual/Materials.html) in Assets
> 2. Assign the **RenderTexture** to the **Material**
> 3. Drag this behaviour to a **GameObject** and attach the material
> 4. Link the .riv asset and **RenderTexture** on the **RiveTexture** (custom script) behaviour
>
> 
# Getting Started
Source: https://rive.app/docs/game-runtimes/unity/getting-started
Adding Rive to your Unity project.
[YouTube video player](https://www.youtube.com/embed/DpmsragqAxM)
New to Rive? Start with the [Rive Editor](/docs/editor/fundamentals/overview) to create your graphics, then [export for runtime](/docs/editor/exporting/exporting-for-runtime) when you're ready to bring them into Unity.
> [card] [Rive Editor basics](/docs/editor/fundamentals/overview)
>
> Create, rig, and build interactive Rive graphics in the editor.
> [card] [Unity runtime overview](/docs/game-runtimes/unity/unity)
>
> Supported Unity versions, graphics backends, and feature support.
## Example projects
To quickly experiment with Rive in Unity, run one of our [example projects](https://github.com/rive-app/rive-unity-examples).
## Installation
The Rive Unity package is available on the Unity Asset Store and on GitHub.
The **Unity Asset Store** has a simpler installation process and only includes the stable package releases. Installing from **GitHub** gives you access to stable releases as well as canary tags, which are updated more frequently and may include [newer/early access features](/docs/feature-support) before they land in a stable release.
> [tab] Unity Asset Store
>
> Install the package from the Unity Asset Store:
>
> * [Rive for Unity (Asset Store)](https://assetstore.unity.com/packages/tools/gui/rive-350858)
>
> **Step 1**
>
> Open Window -> Package Manager
>
> **Step 2**
>
> Select My Assets
>
> **Step 3**
>
> Find Rive and select Download / Import
> [tab] GitHub
>
> The [rive-unity package](https://github.com/rive-app/rive-unity) is also available to install from GitHub using a git dependency.
>
> Add it via **Window -> Package Manager** and choose **Add package from git URL...** (replace `0.0.0` with the [latest release](https://github.com/rive-app/rive-unity/releases)):
>
> ```bash theme={null}
> https://github.com/rive-app/rive-unity.git?path=package#v0.0.0
> ```
>
> **Step 1**
>
> Paste the URL with a version tag 
>
> > [!NOTE]
> >
> > Unity can occasionally crash when upgrading the packages while the Editor is running. If you experience this, close Unity first, update the version in `Packages/manifest.json`, then reopen the project.
>
> You can add it manually to your project's `Packages/manifest.json` (replace `0.0.0` with the [latest release](https://github.com/rive-app/rive-unity/releases)):
>
> ```json theme={null}
> "app.rive.rive-unity": "https://github.com/rive-app/rive-unity.git?path=package#v0.0.0"
> ```
## Adding a Rive file to Unity
See our documentation on [Exporting](/docs/editor/exporting/exporting-for-runtime) graphics for runtime.
Once you have a `.riv` file, drag it into the Unity **Project** window. Unity will import it and automatically create a **Rive Asset** you can reference from components and scripts.
On the [Marketplace](https://rive.app/marketplace), you can find Rive files that can be remixed.
## Displaying a Rive file
**Drag-and-Drop**
To display a Rive file in UI, drag it into the **Scene Hierarchy**. This creates a screen-space setup inside a uGUI Canvas.
> [!NOTE]
>
> The `com.unity.ugui` package must be installed to use these components. This is usually included by default in new Unity projects.
To display a Rive file on a mesh, drop the Rive file onto an existing GameObject with a `MeshRenderer`. This creates a **Rive Panel** and adds a **Rive Texture Renderer** component to the mesh GameObject.
**Quick Creation Menu**
Right-click in the scene hierarchy to create the following:
* `Rive > Rive Panel` - Creates a standalone panel
* `Rive > Rive Panel (Canvas)` - Creates a UI-ready panel
* `Rive > Widgets > Rive Widget` - Adds a standard Rive widget
## Next steps
> [card] [Fundamentals](/docs/game-runtimes/unity/fundamentals)
>
> How files, artboards, and state machines are represented in Unity.
> [card] [Components](/docs/game-runtimes/unity/components)
>
> Rive Panel, Rive Widget, and recommended component-based workflows.
> [card] [Data Binding](/docs/game-runtimes/unity/data-binding)
>
> Bind your C# scripts to your Rive graphics for UI and gameplay-driven updates.
> [card] [Best Practices](/docs/game-runtimes/unity/best-practices)
>
> Performance and usage considerations for Rive in Unity.
# Layouts
Source: https://rive.app/docs/game-runtimes/unity/layouts
Control the layout of your Rive animation in Unity
For more information on creating Rive Layouts, see the [editor documentation](/docs/editor/layouts/layouts-overview).
## The Fit Mode
A Rive graphic authored in the editor will not necessarily match the size of the container it is rendered into at runtime. We need to determine the behavior for this scenario, as no one size fits all.
The solution is choosing the fit mode. This is specified on the container and controls how Rive is scaled.
* `Layout`: Use the Rive layout engine to apply responsive layout to the artboard, matching the container dimensions. For this to work, the artboard must be designed with layouts in mind. See [Responsive Layouts](#responsive-layouts) for more information on how to use this option.
* `Contain`: **(Default)** Preserve aspect ratio and scale the artboard so that its larger dimension matches the corresponding dimension of the container.
If aspect ratios are not identical, this will leave space on the shorter dimension's axis.
* `ScaleDown`: Preserve aspect ratio and behave like `Contain` when the artboard is larger than the container. Otherwise, use the artboard's original dimensions.
* `Cover`: Preserve aspect ratio and scale the artboard so that its smaller dimension matches the corresponding dimension of the container.
If aspect ratios are not identical, this will clip the artboard on the larger dimension's axis.
* `FitWidth`: Preserve aspect ratio and scale the artboard width to match the container's width.
If the aspect ratios between the artboard and container do not match, this will result in either vertical clipping or space in the vertical axis.
* `FitHeight`: Preserve aspect ratio and scale the artboard height to match the container's height.
If the aspect ratios between the artboard and container do not match, this will result in either horizontal clipping or space in the horizontal axis.
* `Fill`: Do not preserve aspect ratio and stretch to the container's dimensions.
* `None`: Do not scale. Use the artboard's original dimensions.
For either dimension, if the artboard's dimension is larger, it will be clipped. If it is smaller, it will leave space.
### Alignment
In all options other than `Layout` and `Fill`, there is the possibility that the Rive graphic is clipped or leaves space within its container. Alignment determines how content aligns within the container. The following options are available.
* `TopLeft`
* `TopCenter`
* `TopRight`
* `CenterLeft`
* `Center` **(Default)**
* `CenterRight`
* `BottomLeft`
* `BottomCenter`
* `BottomRight`
## Applying the Fit and Alignment
> [tab] Components
>
> Using a **Rive Widget** component, you can select from a list of **Fit** and **Alignment** options.
>
> 
> [tab] Legacy API
>
> > [!WARNING]
> >
> > Using the low-level API is no longer recommended. Please use the [Component API](/docs/game-runtimes/unity/components) instead for ease of use and maintainability. This content is provided for legacy support only.
>
> The **fit** and **alignment** can be controlled on the **Rive.Renderer** `.Align()` method:
>
> ```cs theme={null}
> public Fit fit = Fit.contain;
> public Alignment alignment = Alignment.Center;
> public RenderTexture renderTexture;
> private Rive.Renderer m_riveRenderer;
>
> ...
>
> m_renderQueue = new Rive.RenderQueue(renderTexture);
> m_riveRenderer = m_renderQueue.Renderer();
> ...
>
> if (m_artboard != null && renderTexture != null)
> {
> m_riveRenderer.Align(fit, alignment, m_artboard);
> m_riveRenderer.Draw(m_artboard);
> }
> ```
## Responsive layouts
The `Layout` **Fit** mode lets you display resizable artboards with built-in responsive behavior, configured directly in the graphic. Set a **Fit** of type **Layout** at runtime and the artboard will resize automatically. Optionally, provide a **Layout Scale Factor** to further adjust the scale of the content.
> [tab] Components
>
> When **Fit** is set to `Layout`, the **Rive Widget**:
>
> • Measures the available space from its RectTransform.
>
> • Calculates a new artboard size based on both the `Layout Scaling Mode` and a `Layout Scale Factor`.
>
> • Dynamically resizes the artboard to match the calculated dimensions.
>
> ## Layout Scaling Modes
>
> You can choose from three layout scaling modes:
>
> **Reference Artboard Size (Default)**
>
> • Scales the artboard proportionally based on its original (reference) size, preserving the same relative size across different resolutions.
>
> • The artboard always appears “the same size in proportion to the screen,” maintaining consistent, resolution-agnostic visuals.
>
> • Use the Layout Scale Factor to fine-tune or amplify the layout scaling above or below 1×.
>
> **Constant Pixel Size**
>
> • The artboard maintains its pixel size, regardless of the screen resolution or DPI.
>
> • The Layout Scale Factor is a direct multiplier on the pixel size of the original artboard.
>
> • This mode can cause the artboard to appear larger on lower-resolution screens and smaller on higher-resolution screens.
>
> **Constant Physical Size**
>
> • Attempts to maintain the artboard’s physical dimensions across different devices by scaling according to DPI.
>
> • A device with a higher DPI will see larger pixel scaling so that, physically, the artboard is the same size from device to device.
>
> • Requires two additional properties in RiveWidget:
>
> * Fallback DPI: Used if Screen.dpi is unavailable.
> * Reference DPI: The baseline DPI for your UI (e.g., 96 if you’re targeting standard desktop size).
>
> ## Layout Scale Factor
>
> Regardless of which `Layout Scaling Mode` you select, you can further scale the artboard via the `Layout Scale Factor`. A value of 1.0 means no additional scaling; values greater than 1.0 enlarge the artboard, and values below 1.0 shrink it.
>
> In practice, you might use this factor to give yourself flexibility in adjusting the artboard size, even after choosing a particular scaling mode. For example, you might find that everything is slightly too large on mobile and set the Layout Scale Factor to 0.9 (90% of the scaled size).
> [tab] Legacy API
>
> > [!WARNING]
> >
> > Using the low-level API is no longer recommended. Please use the [Component API](/docs/game-runtimes/unity/components) instead for ease of use and maintainability. This content is provided for legacy support only.
>
> **Implementing Layout in Custom Scripts**
>
> When implementing `Fit.Layout` in your custom scripts, consider the following aspects:
>
> 1. **Screen Resolution and Scaling**
>
> * Monitor screen resolution changes
>
> * Handle DPIs
>
> * Implement proper scaling for different display densities
>
> 2. **Input Handling**
>
> * Transform input coordinates to match the scaled layout
> * Account for different DPIs when processing touch/mouse input
> * Consider hit-testing adjustments for scaled elements This [script](https://github.com/rive-app/rive-unity/blob/main/examples/basic/Assets/GameRuntime/RiveScreen.cs) shows one way you could implement `Fit.Layout` support while considering the points mentioned above.
# Listeners
Source: https://rive.app/docs/game-runtimes/unity/listeners
Enable listeners on your Rive animation in Unity
For more information on Rive Listeners see the [editor documentation](/docs/editor/state-machine/listeners).
> [card] [Listeners](/docs/editor/state-machine/listeners)
>
> Listeners give designers the tools to take their State Machine one step further and define click, hover, and mouse move actions that can change properties in the editor and at runtime without the need for a developer.
> [tab] Components
>
> [Panel Renderers](/docs/game-runtimes/unity/components#panel-renderers) are responsible for passing pointer input to **Rive Panels.**
>
> **Requirements**
>
> * Set the `Pointer Input Mode` setting on any **Panel Renderer** to `Enable Pointer Input` if you want a **Rive Panel** to receive pointer events.
>
> * Add an **EventSystem** to the scene. This provides input from Unity to the Panel Renderers and allows them to support any input system in Unity (as long as it uses the EventSystem)
>
> * For the **Rive Canvas Renderer**, ensure the parent Canvas has a **Graphics Raycaster** attached.
>
> * For the **Rive Texture Renderer**, ensure the event camera has a **Physics Raycaster** component attached.
>
> > [!WARNING]
> >
> > The GameObject with the **Rive Texture Renderer** attached must also have a **MeshCollider** attached.
>
> ### Hit Testing
>
> Hit testing controls how pointer events interact with **Rive Widgets** and the content behind them. You can configure this behavior using the `Hit Test Behavior` setting on your **Rive Widget**:
>
> * **Opaque**: The widget blocks all pointer events within its bounds, regardless of whether there's an interactive element (listener) at the pointer location. Content behind the widget won't receive any pointer events.
>
> * **Translucent**: The widget only blocks pointer events where there's an interactive element (listener) at the pointer location. If no listener is hit, the event passes through to content behind the widget.
>
> * **Transparent**: All pointer events pass through to content behind the widget, but Rive listeners still detect and respond to pointer events. This allows simultaneous interaction with both the widget and background content.
>
> * **None**: The widget doesn't perform any hit testing and ignores all pointer events.
>
> This flexibility allows you to create layered interactive experiences while controlling precisely how pointer events are handled at each layer.
> [tab] Legacy API
>
> > [!WARNING]
> >
> > Using the low-level API is no longer recommended. Please use the [Component API](/docs/game-runtimes/unity/components) instead for ease of use and maintainability. This content is provided for legacy support only.
>
> ## Pointer Positions
>
> In rive-unity pointer (mouse/touch) events can be passed to an artboard to enable Rive Listeners. This is accomplished by translating the pointer position to an artboard's local coordinate.
>
> For a complete example see the **getting-started** project in the [examples repository](https://github.com/rive-app/rive-unity-examples) and open a sample scenes:
>
> * **DrawToCameraScene**: Pointer events on a camera
> * **DrawToCubeScene**: Pointer events on a mesh
>
> #### Camera Hit Test
>
> See the **DrawToCameraScene** scene in the **getting-started** project from the [example repository](https://github.com/rive-app/rive-unity-examples).
>
> 
>
> This code snippet demonstrates translating mouse position on the camera to an artboard.
>
> ```csharp theme={null}
> private Artboard m_artboard;
> private StateMachine m_stateMachine;
>
> ...
>
> Camera camera = gameObject.GetComponent();
> if (camera != null)
> {
> Vector3 mousePos = camera.ScreenToViewportPoint(Input.mousePosition);
> Vector2 mouseRiveScreenPos = new Vector2(
> mousePos.x * camera.pixelWidth,
> (1 - mousePos.y) * camera.pixelHeight
> );
> if (m_artboard != null && m_lastMousePosition != mouseRiveScreenPos)
> {
> Vector2 local = m_artboard.LocalCoordinate(
> mouseRiveScreenPos,
> new Rect(0, 0, camera.pixelWidth, camera.pixelHeight),
> fit,
> alignment
> );
> m_stateMachine?.PointerMove(local);
> m_lastMousePosition = mouseRiveScreenPos;
> }
> if (Input.GetMouseButtonDown(0))
> {
> Vector2 local = m_artboard.LocalCoordinate(
> mouseRiveScreenPos,
> new Rect(0, 0, camera.pixelWidth, camera.pixelHeight),
> fit,
> alignment
> );
> m_stateMachine?.PointerDown(local);
> m_wasMouseDown = true;
> }
> else if (m_wasMouseDown)
> {
> m_wasMouseDown = false;
> Vector2 local = m_artboard.LocalCoordinate(
> mouseRiveScreenPos,
> new Rect(0, 0, camera.pixelWidth, camera.pixelHeight),
> fit,
> alignment
> );
> m_stateMachine?.PointerUp(local);
> }
> }
> ```
>
> #### Mesh Hit Test
>
> See the **DrawToCubeScene** scene in the **getting-started** project from the [example repository](https://github.com/rive-app/rive-unity-examples)
>
> 
>
> This code snippet demonstrates translating a [RaycastHit](https://docs.unity3d.com/ScriptReference/RaycastHit.html) on an object to an artboard's local coordinates.
>
> > [!NOTE]
> >
> > The **GameObject** must have a **MeshCollider** attached.
>
> ```csharp theme={null}
> void HitTesting()
> {
> Camera camera = Camera.main;
>
> if (camera == null || renderTexture == null || m_artboard == null) return;
>
> if (!Physics.Raycast(camera.ScreenPointToRay(Input.mousePosition), out RaycastHit hit))
> return;
>
> Renderer rend = hit.transform.GetComponent();
> MeshCollider meshCollider = hit.collider as MeshCollider;
>
> if (rend == null || rend.sharedMaterial == null || rend.sharedMaterial.mainTexture == null || meshCollider == null)
> return;
>
> Vector2 pixelUV = hit.textureCoord;
>
> pixelUV.x *= renderTexture.width;
> pixelUV.y *= renderTexture.height;
>
> Vector3 mousePos = camera.ScreenToViewportPoint(Input.mousePosition);
> Vector2 mouseRiveScreenPos = new(mousePos.x * camera.pixelWidth, (1 - mousePos.y) * camera.pixelHeight);
>
> if (m_lastMousePosition != mouseRiveScreenPos || transform.hasChanged)
> {
> Vector2 local = m_artboard.LocalCoordinate(pixelUV, new Rect(0, 0, renderTexture.width, renderTexture.height), fit, alignment);
> m_stateMachine?.PointerMove(local);
> m_lastMousePosition = mouseRiveScreenPos;
> }
> if (Input.GetMouseButtonDown(0))
> {
> Vector2 local = m_artboard.LocalCoordinate(pixelUV, new Rect(0, 0, renderTexture.width, renderTexture.height), fit, alignment);
> m_stateMachine?.PointerDown(local);
> m_wasMouseDown = true;
> }
> else if (m_wasMouseDown)
> {
> m_wasMouseDown = false; Vector2 local = m_artboard.LocalCoordinate(mouseRiveScreenPos, new Rect(0, 0, renderTexture.width, renderTexture.height), fit, alignment);
> m_stateMachine?.PointerUp(local);
> }
> }
> ```
# Loading Assets
Source: https://rive.app/docs/game-runtimes/unity/loading-assets
Out-of-band assets in Rive Unity.
> [!NOTE]
>
> Only **embedded** and **referenced** assets are supported in Rive Unity; **hosted** assets are not currently supported.
> [!NOTE]
>
> Only **png** and **jpeg** image assets are supported. Support for **webp** is in progress.
## Asset export options
Within the Rive Editor, you can select an asset (for example, an image or font) in the **Asset Panel** and configure the export option for that asset. A Rive file can have a mixture of **embedded**, **referenced**, and **hosted** assets.

**Embedded** assets are included with the exported `.riv` binary file, while **referenced** assets are packaged separately and must be linked at runtime. Using **referenced** assets enables you to reuse the same asset across multiple animation files or in other parts of your game. This reduces the size of your `.riv` file and the resources needed to run your animations that use a shared asset.
### Embedded assets
Any asset marked as embedded will automatically be loaded, and you do not need to do anything to configure the asset.

By selecting the riv file you'll get information on the file's assets in the **Unity Inspector**. The example image above shows an embedded font called "Roboto Flex" with a size of 1MB.
### Referenced assets
Referenced assets need to be linked at runtime. The rive-unity package automatically handles the linking by attempting to find assets within the same directory that match the correct **Name** + **ID** combination. If an asset that matches the criteria is discovered, that asset is automatically converted to a Rive asset and linked.
> [!NOTE]
>
> For an asset to be discoverable and linked, the riv file and asset must be in the same Unity directory.
#### Let's take a look at an example
When exporting your runtime file from the Rive Editor, the `.riv` file and referenced assets are exported in a zip.

The extracted zip has an `acqua_text.riv` file with a referenced asset named `Roboto Flex-887377.ttf`. The referenced asset file name breaks down as such:
* **Name:** Roboto Flex
* **ID:** 887377
Selecting both files (or the entire folder) and dragging them into the **Unity Assets** folder will automatically link the embedded font file - if the **Name** + **ID** matches what the `.riv` file expects.

In the **Unity Inspector** for the Rive file, you can note that the **Asset** for the "Roboto Flex" font has been linked, and the **Roboto Flex** font file has also been converted to a Rive asset.
This example automatically converted and linked the font file because the animation and font files were added simultaneously. Alternatively, you can add the asset file first and then the riv file.; this will result in the same outcome.
If an asset was added after the riv file, you'll need to manually reimport the riv file by **right-clicking** it and selecting **Reimport**.

#### Selecting an importer
Alternatively, you can set the desired Importer for an asset by selecting the correct option in the Inspector. This means you can make an asset a Rive Asset or change back an incorrectly converted asset.

#### Sharing assets
Reusing the same asset in your Rive files should result in a consistent **Name** + **ID** generation when exporting from the Rive Editor.
If a matching asset is not found when importing in Unity, there is a fallback to converting and linking a file that matches only the **Name**. You can optionally use this approach to have more control over asset importing, as an asset filename can be renamed in the Rive Editor.

# Procedural Rendering
Source: https://rive.app/docs/game-runtimes/unity/procedural-rendering
Procedurally draw shapes and paths in Unity using Rive
In this section, you’ll learn how to create custom paint and path objects. This enables you to perform custom computed draw commands using the Rive Renderer.
## Overview
The following classes are available:
* **BlendMode**: determines how the source pixels are blended with the destination pixels.
* **Color**: determines the color of the shape.
* **Gradient**: determines the color gradient of the shape (`LinearGradient` or `RadialGradient`)
* **Paint**: describes how to draw a shape - see [**Paint**](#paint).
* **PaintingStyle**: determines if the shape is filled or stroked.
* **Path**: defines a shape's outline or a clipping mask - see [**Path**](#path).
* **StrokeCap**: determines how the path's endpoints are drawn.
* **StrokeJoin**: the kind of finish to place on the joins between segments.
### RenderQueue
Create a `Rive.RenderQueue` and a `Rive.Renderer`:
```csharp theme={null}
public RenderTexture renderTexture;
private Rive.RenderQueue m_renderQueue;
private Rive.Renderer m_riveRenderer;
...
m_renderQueue = new RenderQueue(renderTexture);
m_riveRenderer = m_renderQueue.Renderer();
```
Call `draw` on the render queue and pass in a `Path` and `Paint` object.
```csharp theme={null}
m_path = new Path();
m_paint = new Paint();
m_riveRenderer.Draw(m_path, m_paint);
```
### Path
A path is a series of drawing commands. The path is used to define a shape's outline or a clipping mask.
Create a new path:
```csharp theme={null}
m_path = new Path();
```
The `Path` class provides various methods to construct a path:
* `moveTo`: Moves the current point to the given point.
* `lineTo`: Adds a straight line from the current point to the given point.
* `circle`: Adds a circle to the path.
* `cubicTo`: Adds a cubic bezier curve to the path.
* `quadTo`: Adds a quadratic bezier segment that curves from the current point.
* `addPath`: Adds the sub-paths of path to this path, transformed by the provided matrix.
* `close`: Closes the path. This will draw a line from the current point to the first point in the path.
* `reset`: Resets the path to an empty state.
* `flush`: to flush the path to native memory.
### Paint
Paint is used to describe how to draw a shape.
Create a new paint:
```csharp theme={null}
m_paint = new Paint();
```
The paint describes the color, gradient, style, thickness, blend mode, stroke cap, and stroke join for a shape.
Call `.Flush()` to flush the paint to native memory. See the [Example ](/docs/game-runtimes/unity/procedural-rendering#example)below.
## Example
This example demonstrates drawing an animated triangle to a [RenderTexture](https://docs.unity3d.com/ScriptReference/RenderTexture.html).

Rive Unity: Procedural Rendering
The `MonoBehaviour` to create the above:
```csharp theme={null}
using System.Collections;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEditor;
using Rive;
public class RiveProcedural : MonoBehaviour
{
public RenderTexture renderTexture;
private Rive.RenderQueue m_renderQueue;
private Rive.Renderer m_riveRenderer;
private CommandBuffer m_commandBuffer;
private Camera m_camera;
Path m_path;
Paint m_paint;
private void Start()
{
m_renderQueue = new RenderQueue(renderTexture);
m_riveRenderer = m_renderQueue.Renderer();
m_path = new Path();
m_paint = new Paint();
m_paint.Color = new Rive.Color(0xFFFF0000);
m_paint.Style = PaintingStyle.stroke;
m_paint.Join = StrokeJoin.round;
m_paint.Thickness = 20.0f;
m_riveRenderer.Draw(m_path, m_paint);
m_commandBuffer = new CommandBuffer();
m_commandBuffer.SetRenderTarget(renderTexture);
m_riveRenderer.AddToCommandBuffer(m_commandBuffer);
m_camera = Camera.main;
if (m_camera != null)
{
Camera.main.AddCommandBuffer(CameraEvent.AfterEverything, m_commandBuffer);
}
}
private void Update()
{
if (m_path == null)
{
return;
}
m_path.Reset();
float expand = Time.fixedTime * 10;
m_path.MoveTo(256, 256 - 100 - expand);
m_path.LineTo(256 + 50 + expand, 256 + 50 + expand);
m_path.LineTo(256 - 50 - expand, 256 + 50 + expand);
m_path.Close();
m_path.Flush();
m_paint.Thickness = (Mathf.Sin(Time.fixedTime * Mathf.PI * 2) + 1.0f) * 20.0f + 1.0f;
m_paint.Flush();
}
private void OnDisable()
{
if (m_camera != null && m_commandBuffer != null)
{
m_camera.RemoveCommandBuffer(CameraEvent.AfterEverything, m_commandBuffer);
}
}
}
```
### Additional resources
See the **getting-started** project in the examples repository for a complete example and open the **ProceduralRenderingScene** scene.
# Runtime Asset Swapping
Source: https://rive.app/docs/game-runtimes/unity/runtime-asset-swapping
For most dynamic asset swapping use cases, we recommend [data binding](/docs/game-runtimes/unity/data-binding). Data binding changes only the bound property, so different parts of the graphic can use different images or fonts.
> [card] [Data Binding Images](/docs/game-runtimes/unity/data-binding#images)
>
> Swap a specific image property at runtime without replacing the file-level asset.
> [card] [Data Binding Fonts](/docs/game-runtimes/unity/data-binding#fonts)
>
> Swap a specific font property at runtime so bound text can use different typefaces.
This page explains how to use the `CustomAssetLoaderCallback` to swap fonts, images, or audio assets at the file level within a Rive file.
This approach is useful when you want your replacement asset to be used everywhere the original appears throughout the file. For example, if you need to replace a font globally, so that all text that uses that font updates automatically, you can do so in one place instead of configuring individual property bindings for each instance.
## Setting up asset loading
To swap assets at runtime, provide a callback when loading your Rive file:
```csharp theme={null}
File.Load(Asset asset, CustomAssetLoaderCallback customAssetLoaderCallback);
File.Load(TextAsset asset, CustomAssetLoaderCallback customAssetLoaderCallback);
File.Load(byte[] riveFileByteContents, CustomAssetLoaderCallback customAssetLoaderCallback);
```
Your callback will be invoked whenever the runtime needs to load an asset. The callback should return `true` if you've handled the asset loading, or `false` to let the runtime handle it using the default loading behavior.
Here's an example showing how you might swap a font at runtime:
```csharp theme={null}
private FontOutOfBandAsset m_fontOobAsset;
private File m_file;
FontEmbeddedAssetReference fontEmbeddedAssetReference
private bool OobAssetLoaderDelegate(EmbeddedAssetReference assetReference)
{
// Keep a reference to the fontEmbeddedAssetReference so we can update the font again later
fontEmbeddedAssetReference = assetReference as FontEmbeddedAssetReference;
if (fontEmbeddedAssetReference != null)
{
fontEmbeddedAssetReference.SetFont(m_fontOobAsset);
return true;
}
return false;
}
private void Start()
{
m_fontOobAsset.Load();
m_file = Rive.File.Load(asset, OobAssetLoaderDelegate);
// You could call fontEmbeddedAssetReference.SetFont() here again to change the font
}
private void OnDestroy()
{
m_fontOobAsset.Unload();
m_file.Dispose();
}
```
#### Overload with fallback
An overload of `Rive.File.Load()` includes a `fallbackToAssignedAssets` parameter.
If set to `true `and your custom loader doesn't handle a certain asset, the runtime will look for references assigned to your Rive asset in the Unity Inspector and automatically load them if they exist. This is handy when you only want to replace some assets and rely on default references for the rest.
```csharp theme={null}
var file = File.Load(myRiveAsset, MyCustomAssetLoader, fallbackToAssignedAssets: true);
```
## Asset types
You can swap these types of assets at runtime:
* `FontOutOfBandAsset`: For font files
* `ImageOutOfBandAsset`: For image files
* `AudioOutOfBandAsset`: For audio files
## Asset reference types
When handling assets in your callback, you'll need to check the type of the `EmbeddedAssetReference` before setting the asset. Each asset type has its own reference class with specific setter methods:
```csharp theme={null}
private bool AssetLoaderDelegate(EmbeddedAssetReference assetReference)
{
// Handle font assets
if (assetReference is FontEmbeddedAssetReference fontReference)
{
fontReference.SetFont(myFontAsset);
return true;
}
// Handle image assets
if (assetReference is ImageEmbeddedAssetReference imageReference)
{
imageReference.SetImage(myImageAsset);
return true;
}
// Handle audio assets
if (assetReference is AudioEmbeddedAssetReference audioReference)
{
audioReference.SetAudio(myAudioAsset);
return true;
}
return false;
}
```
## Memory management
When working with runtime asset swapping, we recommend following these best practices:
1. Always call `Load()` on your Out-Of-Band asset before using it in the callback
2. Dispose of resources properly:
* Call `Unload()` on your assets when they're no longer needed
* Call `Dispose()` on the Rive file when you're done with it
## Creating out-of-band assets dynamically
If you have an asset that isn't in your Unity project at build time (for example, if you're loading an image from a CDN), you can create an out-of-band asset at runtime using the `OutOfBandAsset.Create()` method. Here, the `bytes` parameter should be the raw file data for the asset.
This works for fonts, images, and audio, as long as you use the appropriate type (`FontOutOfBandAsset`, `ImageOutOfBandAsset`, or `AudioOutOfBandAsset`).
```
byte[] imageBytes = /* fetched from a CDN or elsewhere */;
var myImageAsset = OutOfBandAsset.Create(imageBytes);
```
## Example
For a demo of runtime asset swapping in Unity, see the **Image Swapping** scene in the [Rive Unity Examples repository](https://github.com/rive-app/rive-unity-examples).
# State Machines
Source: https://rive.app/docs/game-runtimes/unity/state-machines
For more information on designing and building state machines in the Rive editor, please refer to [State Machine Overview](/docs/editor/state-machine).
A Rive state machine is a set of animation states and the transitions between them. At runtime there is limited ability to observe or modify the state directly. This is by design, as this would limit the ability of a designer in Rive to modify the state machine without creating breaking changes. Instead, state machines are indirectly controlled through transitions conditioned on [Data Binding](data-binding) properties.
A designer assigns a default state machine for each artboard in the Rive editor. They may create multiple state machines, each representing a different configuration of states and transitions. When rendering a Rive file and artboard, you may choose which state machine to play. If no state machine is specified, the default state machine for that artboard is used.
## Controlling playback
State machines play by "advancing" over time. This is done once per frame by the amount of time between frames. For example, for a graphic running at 60 frames per second, the state machine would be advanced by approximately 16.67 milliseconds (1/60th of a second) each frame. This advancing evaluates keyframes, transitions, data bindings changes, and ultimately the visible artboard elements to create the illusion of motion over time.
This runtime provides a way to control whether the state machine is playing. When paused or stopped, the state machine does not advance and the last rendered frame remains visible. When playing from pause, the state machine resumes from where it left off, whereas when playing from stop, it restarts from the entry state.
In addition to the paused/stopped state, state machines may also "settle". This is an optimization where the Rive runtime detects that no further changes will occur (for example, if there are no active transitions or animations). While settled the state machine will also stop advancing. This improves performance and energy use by avoiding unnecessary calculations. State machines are unsettled by external actions that change their state, such as user input or data binding changes. You can additionally force a state machine to unsettle by calling play, though it may immediately re-settle if there is no further work to be done.
## Overview
A StateMachine advances (plays) animations in an Artboard.
> [tab] Components
>
> A **Rive Widget** automatically loads and advances the state machine from [your artboard configuration settings](/docs/game-runtimes/unity/fundamentals#artboards). Here's how you can access the loaded state machine in your scripts:
>
> ```csharp theme={null}
> [SerializeField] private RiveWidget m_riveWidget;
>
> ...
>
> void OnEnable()
> {
> m_riveWidget.OnWidgetStatusChanged += OnWidgetStatusChanged;
> }
>
> private void OnWidgetStatusChanged()
> {
> // Wait for the Rive Widget to load before accessing the state machine.
> if (m_riveWidget.Status == WidgetStatus.Loaded)
> {
> StateMachine m_stateMachine = m_riveWidget.StateMachine;
> }
> }
>
>
> void OnDisable()
> {
> m_riveWidget.OnWidgetStatusChanged -= OnWidgetStatusChanged;
> }
> ```
> [tab] Legacy API
>
> > [!WARNING]
> >
> > Using the low-level API is no longer recommended. Please use the [Component API](/docs/game-runtimes/unity/components) instead for ease of use and maintainability. This content is provided for legacy support only.
>
> State Machines are instantiated from an Arboard instance:
>
> ```csharp theme={null}
> private StateMachine m_stateMachine;
>
> ...
>
> m_stateMachine = m_artboard?.StateMachine(); // default state machine
> m_stateMachine = m_artboard?.StateMachine(0); // state machine at index
> m_stateMachine = m_artboard?.StateMachine("Name"); // state machine with name
> ```
>
> The state machine is played by calling `advance` and passing in the delta time:
>
> ```csharp theme={null}
> private void Update()
> {
> m_stateMachine?.Advance(Time.deltaTime);
> }
> ```
# Control a health bar with data binding in Unity
Source: https://rive.app/docs/game-runtimes/unity/tutorials/health-bar
Learn how to connect Unity gameplay data to a Rive health bar using view model instance properties.
Beginner
This tutorial walks through connecting a Rive health bar file to Unity using [Data Binding](/docs/editor/data-binding/overview). In this setup, your Unity code updates a single number (`health`) while the Rive file handles the visuals in response (e.g. color changes, and low-health warnings).

To view the completed project, see [HealthBar Demo](https://github.com/rive-app/rive-unity-examples/blob/main/getting-started/Assets/Demos/HealthBar).
## What you'll build
* A scene that displays a Rive health bar file in screen space
* A `HealthBarController` script that:
* Sets a `health` **number** property on the view model instance
* Listens for a `gameOver` **trigger** fired from the Rive file
* (Optional) A small keyboard control script to test damage/heal
## Requirements
* A Unity project with the Rive package installed (see [Getting Started](/docs/game-runtimes/unity/getting-started))
* Familiarity with view models and [data binding](/docs/game-runtimes/unity/data-binding) in Rive
* A `.riv` file that exposes a view model instance with:
* `health` (Number)
* `gameOver` (Trigger)
For this tutorial, you can use the demo health bar file available on the [Marketplace](https://rive.app/marketplace/24637-health-bar-data-binding-quick-start/). Click **Download** to get the `.riv` file, or click **Preview in Rive** to see how it was set up in the Rive Editor.
## 1. Import the Rive file

Drag your `.riv` file into the Unity **Project** window. Unity will import it and create a **Rive Asset**.
## 2. Display the Rive file in UI

Create a new scene if you haven't already, then drag the **Rive Asset** into the **Scene Hierarchy** to create a Rive Panel/Widget that renders to a uGUI Canvas.
This will also add an **Event System** to the scene, which is required for the Rive Widget to receive pointer events.
## 3. Configure the Rive Widget

The **Rive Widget** should already be configured with the default artboard, state machine, and **Auto Bind Default** mode. If these aren't set correctly, configure them in the inspector:
**Step 1**
Select the correct **Artboard Name** and **State Machine Name** for your health bar file.
For this tutorial, the selected artboard name should be `health_bar_v01` and the state machine name should be `State Machine 1`.
**Step 2**
Set **Data Binding Mode** to **Auto Bind Default**.
> [!NOTE]
>
> The demo file was built with responsiveness in mind, so we also set the `Fit` mode to `Layout` to ensure the health bar is scaled to the size of the widget. See [Layout](/docs/game-runtimes/unity/layouts) to learn more.
## 4. Add the controller script
Create a C# script named `HealthBarController.cs`. This is a wrapper script that will be used to control the health bar from your gameplay code.
Why use a wrapper script? Even though you *can* access Rive view model instance properties anywhere in your project, it's usually better to keep that logic in one place because:
* **It keeps the rest of your code Rive-agnostic**: your gameplay scripts can call `Damage()` / `Heal()` without knowing about view models, property names, or widget lifecycle.
* **It centralizes Rive-specific details**: if the Rive file changes (renamed properties, new triggers, different setup), you update one script instead of hunting through your project.
### Step 4.1: Set up the basic fields
Start by adding references to the widget and the property names we'll look up in the Rive file.
```csharp theme={null}
using System;
using Rive;
using Rive.Components;
using UnityEngine;
using UnityEngine.Events;
public class HealthBarController : MonoBehaviour
{
[Header("Rive")]
[Tooltip("The Rive Widget that is displaying your health bar file.")]
[SerializeField] private RiveWidget m_riveWidget;
[Header("Initial health")]
[Tooltip("Initial health applied when the widget finishes loading.")]
[SerializeField] private float m_startingHealth = 100f;
[Header("ViewModel Property Names")]
[Tooltip("ViewModel Number property name used by the Rive file.")]
[SerializeField] private string m_healthPropertyName = "health";
[Tooltip("ViewModel Trigger property name fired by the Rive file.")]
[SerializeField] private string m_gameOverPropertyName = "gameOver";
// Cached references to the view model instance properties we'll be using to interact with the Rive file.
private ViewModelInstanceNumberProperty m_healthProperty;
private ViewModelInstanceTriggerProperty m_gameOverProperty;
// Track whether we've initialized health so we don't overwrite it if the widget GameObject is disabled and re-enabled.
private bool m_hasInitialized;
}
```
If you're not sure where to find the values for the `m_healthPropertyName` and `m_gameOverPropertyName` fields, they refer to the names of the `health` and `gameOver` properties in the main view model defined in the Rive file.

The health bar file in the Rive Editor
### Step 4.2: Add events
Add UnityEvents so you can react to health changes and game over events (both in the Inspector and from code).
```csharp theme={null}
[Header("Events")]
[Tooltip("Invoked whenever health changes in the Rive file.")]
public FloatEvent OnHealthChanged = new FloatEvent();
[Tooltip("Invoked when the Rive file fires the gameOver trigger.")]
public UnityEvent OnGameOver = new UnityEvent();
[Serializable]
public class FloatEvent : UnityEvent { }
```
### Step 4.3: Grab the View Model instance properties when the widget is loaded
We use `OnWidgetStatusChanged` to access the view model instance once the widget is loaded. If you try to access the view model instance before the widget is loaded, it will be null.
> [!NOTE]
>
> The `OnWidgetStatusChanged` callback also provides a safe window to set initial values before the first frame renders, ensuring they're visible immediately without delay.
Add the following methods inside `HealthBarController`:
```csharp theme={null}
private void OnEnable()
{
if (m_riveWidget == null)
{
Debug.LogError($"{nameof(HealthBarController)}: No RiveWidget assigned.", this);
return;
}
m_riveWidget.OnWidgetStatusChanged += HandleWidgetStatusChanged;
// If the widget was already loaded before we subscribed, initialize immediately.
HandleWidgetStatusChanged();
}
private void OnDisable()
{
if (m_riveWidget != null)
{
m_riveWidget.OnWidgetStatusChanged -= HandleWidgetStatusChanged;
}
// Clean up event listeners to avoid duplicate subscriptions.
if (m_healthProperty != null)
m_healthProperty.OnValueChanged -= HandleHealthChangedFromRive;
if (m_gameOverProperty != null)
m_gameOverProperty.OnTriggered -= HandleGameOverTriggeredFromRive;
}
private void HandleWidgetStatusChanged()
{
if (m_riveWidget.Status != WidgetStatus.Loaded)
return;
ViewModelInstance viewModelInstance = m_riveWidget.StateMachine?.ViewModelInstance;
if (viewModelInstance == null)
{
Debug.LogError($"{nameof(HealthBarController)}: ViewModelInstance is null. " +
"Make sure Data Binding Mode is set to Auto Bind Default / Selected.", this);
return;
}
// Clean up old listeners first.
if (m_healthProperty != null)
m_healthProperty.OnValueChanged -= HandleHealthChangedFromRive;
if (m_gameOverProperty != null)
m_gameOverProperty.OnTriggered -= HandleGameOverTriggeredFromRive;
// Get the health property by name.
m_healthProperty = viewModelInstance.GetNumberProperty(m_healthPropertyName);
if (m_healthProperty == null)
{
Debug.LogError($"{nameof(HealthBarController)}: Number property '{m_healthPropertyName}' not found.", this);
return;
}
// Get the gameOver property by name.
m_gameOverProperty = viewModelInstance.GetTriggerProperty(m_gameOverPropertyName);
if (m_gameOverProperty == null)
{
Debug.LogError($"{nameof(HealthBarController)}: Trigger property '{m_gameOverPropertyName}' not found.", this);
return;
}
// Subscribe to changes from the Rive file for the health and gameOver properties.
m_healthProperty.OnValueChanged += HandleHealthChangedFromRive;
m_gameOverProperty.OnTriggered += HandleGameOverTriggeredFromRive;
// Set the initial health value only once
if (!m_hasInitialized)
{
m_healthProperty.Value = m_startingHealth;
m_hasInitialized = true;
}
}
// Rive lets you listen for events when properties change or triggers are fired. We invoke our UnityEvents to notify other scripts of the changes.
private void HandleHealthChangedFromRive(float newValue)
{
OnHealthChanged.Invoke(newValue);
}
private void HandleGameOverTriggeredFromRive()
{
OnGameOver.Invoke();
}
```
> [!NOTE]
>
> This tutorial file includes a default view model instance. If the widget's **Data Binding Mode** was set to **Manual** or if the file did not have a default view model instance, `m_riveWidget.StateMachine?.ViewModelInstance` would be null.
>
> In this case, you would need to manually create and bind a new view model instance to the state machine.
>
> Learn more about binding modes and how to configure them in the [Data Binding](/docs/game-runtimes/unity/data-binding#auto-binding-in-the-inspector) documentation.
### Step 4.4: Expose a simple API for gameplay code
Now we add methods that provide a clean interface for gameplay without having to expose the underlying Rive implementation details.
First, add a `Health` property that reads from the `health` view model instance property when available:
```csharp theme={null}
///
/// Health is a thin wrapper over the view model number property.
/// Until the widget is loaded, it returns the starting value.
///
public float Health
{
get
{
// If the widget is loaded, read from the Rive view model instance property
if (m_healthProperty != null)
{
return m_healthProperty.Value;
}
// Widget isn't loaded yet, return the starting value
return m_startingHealth;
}
}
private void WriteHealth(float value)
{
// If the widget is loaded, write to the Rive view model instance property
if (m_healthProperty != null)
{
m_healthProperty.Value = value;
return;
}
// Widget isn't loaded yet. Store it so we can apply it when the view model instance is ready.
m_startingHealth = value;
}
```
Then add gameplay methods that use this helper:
```csharp theme={null}
public void Damage(float amount)
{
WriteHealth(Health - amount);
}
public void Heal(float amount)
{
WriteHealth(Health + amount);
}
```
## 5. Set up the controller in the Inspector

Attach `HealthBarController` to any GameObject (typically the same object as your `Rive Widget`), then:
**Step 1**
Assign the `Rive Widget` field to the one you created earlier.
**Step 2**
Set `Starting Health` to the initial health value you want to display (for example, 70).
**Step 3**
(Optional) Wire `On Game Over` to your own gameplay logic.
### Optional: keyboard controls
If you want a quick way to test this in Play Mode, you can drive the controller with keyboard input.
Create a script named `HealthBarKeyboardControls.cs`:
```csharp theme={null}
using UnityEngine;
using UnityEngine.InputSystem;
public class HealthBarKeyboardControls : MonoBehaviour
{
[SerializeField] private HealthBarController m_healthBar;
[SerializeField] private float m_damageAmount = 10f;
[SerializeField] private float m_healAmount = 20f;
private void Update()
{
var keyboard = Keyboard.current;
if (keyboard == null)
return;
// Damage (left arrow key )
if (keyboard.leftArrowKey.wasPressedThisFrame)
m_healthBar.Damage(m_damageAmount);
// Heal (right arrow key)
if (keyboard.rightArrowKey.wasPressedThisFrame)
m_healthBar.Heal(m_healAmount);
}
}
```
Attach `HealthBarKeyboardControls` to any GameObject, assign your `HealthBarController`, then press:
* `←` (left arrow key) to take damage
* `→` (right arrow key) to heal
> [!NOTE]
>
> This uses Unity's **Input System** package (`com.unity.inputsystem`). If your project is still using the legacy input manager, you'll need to enable the Input System in Unity (**Project Settings → Player → Active Input Handling**).
>
> If the `Event System` in your scene shows a `Replace with InputSystemUIInputModel` button in the Inspector, click it to upgrade to the new Input System (otherwise pointer events won't work with the Rive file).
## 6. Drive health from gameplay code
From your gameplay scripts you can treat the Rive file like a "rendered UI" for your data:
* Call `Damage()` or `Heal()` based on gameplay events.
* Or read `Health` if you need the current value.
The data flow isn't just one-way. Your game scripts can also listen to triggers or changes to values from the Rive file. For example, your game manager script could listen to both health changes and the game over event:
```csharp theme={null}
public class GameManager : MonoBehaviour
{
[SerializeField] private HealthBarController healthBar;
private void Start()
{
// Listen to health value changes
healthBar.OnHealthChanged.AddListener(HandleHealthChanged);
// Listen to game over trigger
healthBar.OnGameOver.AddListener(HandleGameOver);
}
private void HandleHealthChanged(float newHealth)
{
Debug.Log($"Health changed to: {newHealth}");
// Your game logic...
}
private void HandleGameOver()
{
Debug.Log("Game Over!");
// Your game logic...
}
}
```
This approach separates your game logic from visual presentation. As long as you keep the data contract the same (the `health` number and `gameOver` trigger), you can change the health bar's appearance in the Rive Editor as much as you want without updating or writing any additional code. Simply swap out the old .riv file with the new one.
**Final HealthBarController.cs**
```csharp theme={null}
using System;
using Rive;
using Rive.Components;
using UnityEngine;
using UnityEngine.Events;
public class HealthBarController : MonoBehaviour
{
[Header("Rive")]
[Tooltip("The Rive Widget that is displaying your health bar file.")]
[SerializeField] private RiveWidget m_riveWidget;
[Header("Initial health")]
[Tooltip("Initial health applied when the widget finishes loading.")]
[SerializeField] private float m_startingHealth = 100f;
[Header("ViewModel Property Names")]
[Tooltip("ViewModel Number property name used by the Rive file.")]
[SerializeField] private string m_healthPropertyName = "health";
[Tooltip("ViewModel Trigger property name fired by the Rive file.")]
[SerializeField] private string m_gameOverPropertyName = "gameOver";
[Header("Events")]
[Tooltip("Invoked whenever health changes in the Rive file. It is called with the new health value.")]
public FloatEvent OnHealthChanged = new FloatEvent();
[Tooltip("Invoked when the Rive file fires the gameOver trigger.")]
public UnityEvent OnGameOver = new UnityEvent();
[Serializable]
public class FloatEvent : UnityEvent { }
private ViewModelInstanceNumberProperty m_healthProperty;
private ViewModelInstanceTriggerProperty m_gameOverProperty;
// Track whether we've initialized health so we don't overwrite it if the widget GameObject is disabled and re-enabled.
private bool m_hasInitialized;
public float Health
{
get
{
// If the widget is loaded, read from the Rive view model instance property
if (m_healthProperty != null)
{
return m_healthProperty.Value;
}
// Widget isn't loaded yet, return the starting value
return m_startingHealth;
}
}
private void WriteHealth(float value)
{
// If the widget is loaded, write to the Rive view model instance property
if (m_healthProperty != null)
{
m_healthProperty.Value = value;
return;
}
// Widget isn't loaded yet. Store it so we can apply it when the view model instance is ready.
m_startingHealth = value;
}
private void OnEnable()
{
if (m_riveWidget == null)
{
Debug.LogError($"{nameof(HealthBarController)}: No RiveWidget assigned.", this);
return;
}
m_riveWidget.OnWidgetStatusChanged += HandleWidgetStatusChanged;
// If the widget was already loaded before we subscribed, initialize the health bar immediately.
HandleWidgetStatusChanged();
}
private void OnDisable()
{
if (m_riveWidget != null)
{
m_riveWidget.OnWidgetStatusChanged -= HandleWidgetStatusChanged;
}
// Clean up event listeners to avoid duplicate subscriptions.
if (m_healthProperty != null)
m_healthProperty.OnValueChanged -= HandleHealthChangedFromRive;
if (m_gameOverProperty != null)
m_gameOverProperty.OnTriggered -= HandleGameOverTriggeredFromRive;
}
private void HandleWidgetStatusChanged()
{
if (m_riveWidget.Status != WidgetStatus.Loaded)
return;
ViewModelInstance viewModelInstance = m_riveWidget.StateMachine?.ViewModelInstance;
if (viewModelInstance == null)
{
Debug.LogError($"{nameof(HealthBarController)}: ViewModelInstance is null. " +
"Make sure Data Binding Mode is set to Auto Bind Default / Selected.", this);
return;
}
// Clean up old listeners first.
if (m_healthProperty != null)
m_healthProperty.OnValueChanged -= HandleHealthChangedFromRive;
if (m_gameOverProperty != null)
m_gameOverProperty.OnTriggered -= HandleGameOverTriggeredFromRive;
// Get the health property by name.
m_healthProperty = viewModelInstance.GetNumberProperty(m_healthPropertyName);
if (m_healthProperty == null)
{
Debug.LogError($"{nameof(HealthBarController)}: Number property '{m_healthPropertyName}' not found.", this);
return;
}
// Get the gameOver property by name.
m_gameOverProperty = viewModelInstance.GetTriggerProperty(m_gameOverPropertyName);
if (m_gameOverProperty == null)
{
Debug.LogError($"{nameof(HealthBarController)}: Trigger property '{m_gameOverPropertyName}' not found.", this);
return;
}
// Subscribe to changes from the Rive file for the health and gameOver properties.
m_healthProperty.OnValueChanged += HandleHealthChangedFromRive;
m_gameOverProperty.OnTriggered += HandleGameOverTriggeredFromRive;
// Set the initial health value only once
if (!m_hasInitialized)
{
m_healthProperty.Value = m_startingHealth;
m_hasInitialized = true;
}
}
public void Damage(float amount)
{
WriteHealth(Health - amount);
}
public void Heal(float amount)
{
WriteHealth(Health + amount);
}
private void HandleHealthChangedFromRive(float newValue)
{
OnHealthChanged.Invoke(newValue);
}
private void HandleGameOverTriggeredFromRive()
{
OnGameOver.Invoke();
}
}
```
# Unity
Source: https://rive.app/docs/game-runtimes/unity/unity
Unity runtime for Rive.
> [!NOTE]
>
> See [Feature Support](#feature-support) below for an updated list of Rive features in Unity.
## Unity version support
The package supports Unity LTS versions from 2021 upwards (including Unity 6).
## Rendering support
The rive-unity runtime uses the [Rive Renderer](https://rive.app/renderer) and is up to date with the latest C++ runtime version of Rive.
* [WebGL](https://github.com/rive-app/rive-unity/blob/main/WEBGL.md)
* Metal on Mac
* Metal on iOS
* D3D11 on Windows
* OpenGL on Windows
* OpenGL on Android
* Vulkan on Windows
* Vulkan on Android
* Vulkan on Ubuntu 24.04+ (x86_64)
* D3D12
Planned support for:
* Consoles
### Bug reports
If you encounter any errors or unexpected crashes while integrating the Rive Unity runtime, we recommend logging a detailed issue directly to the [rive-unity](https://github.com/rive-app/rive-unity/issues) repo with an **Editor.log** attached to the issue to help provide more details and context about what might have occurred.
You can find more details on where to find your Editor.log file in the [Unity docs](https://docs.unity3d.com/Manual/LogFiles.html).
> [!NOTE]
>
> Note that it is best to grab the Editor.log file immediately after a crash has occurred
## Feature support
The rive-unity runtime uses the latest Rive C++ runtime. For more details on runtime support, see the [Feature Support](/docs/feature-support) page. Refer to the following table for what is currently supported in the Unity runtime.
# Getting Started
Source: https://rive.app/docs/game-runtimes/unreal/getting-started
Install the Rive Unreal plugin, run your first Artboard via URiveActorComponent, and display it in UMG.
This guide walks you through installing the Rive Unreal plugin, importing a `.riv` file, and displaying it in UMG.
> [!NOTE]
>
> **Prerequisites**
>
> * Unreal Engine 5.6 or above.
> * A C++ toolchain. The Rive plugin is a C++ plugin, so it's compiled as part
> of your project regardless of how you install it:
> * **Windows**: Visual Studio 2022 with the **Game development with C++**
> workload (it includes the Windows SDK and .NET components Unreal needs).
> * **macOS**: Xcode with the command-line tools (`xcode-select --install`).
## 1) Install the plugin
> [tab] Fab (Recommended)
>
> **Step 1**
>
> Open the Epic Games Launcher or Unreal Editor.
>
> **Step 2**
>
> Open Fab.
>
> **Step 3**
>
> Search for Rive or go directly to:\
> [https://www.fab.com/listings/3a2968c1-4a1d-427c-934e-92e4d8578b77](https://www.fab.com/listings/3a2968c1-4a1d-427c-934e-92e4d8578b77)
>
> **Step 4**
>
> Add the plugin to your engine or project.
>
> **Step 5**
>
> Restart Unreal Engine if prompted.
> [tab] GitHub
>
> **Step 1**
>
> Clone the repository:
>
> ```bash theme={null}
> git clone https://github.com/rive-app/rive-unreal.git
> ```
>
> **Step 2**
>
> Copy the `Rive` plugin folder into your project's `Plugins/` directory.
## 2) Build the project
The Rive plugin is C++, so your project must be compiled before the editor
can load it.
> [tab] Windows
>
> **Step 1**
>
> Right-click your `.uproject` file and choose **Generate Visual Studio
> project files**.
>
> **Step 2**
>
> Open the generated `.sln` in Visual Studio 2022.
>
> **Step 3**
>
> Set the configuration to **Development Editor** / **Win64** and build.
> [tab] macOS
>
> **Step 1**
>
> Right-click your `.uproject` file and choose **Generate Xcode
> project**.
>
> **Step 2**
>
> Open the generated project in Xcode and build the editor target.
Alternatively, double-click the `.uproject` directly — if the plugin modules
aren't built, Unreal offers to rebuild them; click **Yes**.
## 3) Enable the plugin
1. Open Edit → Plugins.
2. Locate Rive under Runtime.
3. Enable the plugin.
4. Restart the editor if required.
## 4) Import a Rive file
1. Open the Content Browser.
2. Drag and drop a `.riv` file into your project.
Unreal creates a **Rive File** asset. You can inspect this asset by double-clicking it.
> [!NOTE]
>
> A **Rive File** is an Unreal asset. It does not render directly.
> [!WARNING]
>
> The Unreal runtime does not yet support referenced assets. Be sure to embed all assets in the `.riv` file.
## 5) Create a widget
1. Right-click on the **Rive file** asset and select **Create Rive Widget** from the context menu.

You can inspect the created widget by double-clicking it.

## 6) Create a Blueprint
1. You can now use the widget in a blueprint just as you would any other widget.

## 7) Bind a ViewModel
If the Rive File is not using **autobinding**, you must assign a viewmodel. This can be done in blueprints using the **Make View Model** node.

Your **Rive File** is now setup for use in your application. The next page will show you how to observe changes in the ViewModel.

# World-Space RenderTargets
Source: https://rive.app/docs/game-runtimes/unreal/in-world-textures
Drag a Rive RenderTarget into the level to create an in-world surface with an auto-generated material.

The fastest way to put Rive content on a mesh in world space is to use a **Rive RenderTarget** asset.
You can drag a **Rive RenderTarget** directly into the level. Unreal will:
* Spawn an actor in the scene
* Create a material that displays the RenderTarget texture
* Assign the material to the spawned mesh
This workflow is ideal for:
* In-world screens
* Monitors / kiosks
* Control panels
* “TV” surfaces
> [!NOTE]
>
> This page covers world-space RenderTargets.\
> For screen-space UI (HUDs/menus), use **URiveWidget**.
## 1) Create a Rive RenderTarget asset
1. Rigt-click on a Rive file asset.
2. Select **Create Rive Render Target.**
Double clicking the created RenderTarget will open the asset editor in which you can specify:
* **Rive File**
* **Artboard**
* **State Machine** (optional)
* **Size / Resolution**
> [!TIP]
>
> Start with 512×512. Increase only if the screen is large and close to the camera.
## 2) Drag it into the level
Drag the RenderTarget from the Content Browser into the viewport to apply it to a mesh. Unreal will automatically create a material that samples the RenderTarget texture. At this point you should see the Rive content on the surface.
## 3) How updates work (tick + draw)
A RenderTarget is a texture output. It only changes when the runtime is advanced and drawn.
In practice, you must ensure there is a driver in your scene that:
* Advances the runtime (Tick)
* Draws the frame into the RenderTarget (Draw)
> [!WARNING]
>
> If nothing is driving the RenderTarget, it will appear static.
The recommended driver for RenderTargets is **RiveRenderTargetUpdater**, which is designed specifically for in-world textures.
## 4) Driving the RenderTarget with RiveRenderTargetUpdater
If you are using the RenderTarget workflow, place an Actor in the level that owns the runtime and renders to the target.
Typical setup:
1. Create an Actor Blueprint (e.g. `BP_RiveRenderDriver`)
2. Add a **RiveRenderTargetUpdater** component.
3. Point it at the **RenderTarget** in the details pane.
4. Set the RenderTarget size to match your in-world material needs.
> [!NOTE]
>
> **RiveRenderTargetUpdater** is intended for RenderTargets (world-space textures).\
> It is not intended for screen-space widgets.
## 5) Interactivity
If your Rive content is interactive (state machine + view model):
* Bind a ViewModel
* Set ViewModel values
* Fire triggers
The RenderTarget will reflect changes the next time it is driven (tick/draw).
# Observing ViewModel Changes
Source: https://rive.app/docs/game-runtimes/unreal/observing-viewmodel-changes
React to animation and state updates by observing ViewModel property changes.
In the Unreal runtime, **ViewModels** are the supported way for Rive content to communicate back to Unreal.
Legacy **State Machine** events and direct callback mechanisms are deprecated.\
New integrations should observe **ViewModel** property changes instead.
> [!NOTE]
>
> All runtime output from Rive should flow through a **ViewModel Instance**.
## How observation works
During the **Artboard** tick:
1. Unreal sets **ViewModel** values
2. The **State Machine** evaluates transitions
3. The **State Machine** may modify **ViewModel** values
4. Property change callbacks are emitted
5. Rendering occurs
Observation happens synchronously during this update cycle.
## Registering callbacks
Each property on a **ViewModel Instance** can be observed.
When a property changes:
* The callback is invoked
* The updated value is available
* Logic can react immediately
Callbacks should be:
* Registered after creating the **ViewModel Instance**
* Unregistered before destroying the instance
* Owned by the same system that owns the instance
You can use the **Add Field Value Changed Delegate** to trigger events when a value is changed. The following image shows an example of a delegate being added to a **ViewModel** field.

> [!TIP]
>
> Use **Trigger Properties** for actions.\
> Use boolean or numeric properties for persistent state.
## Observing structured data
Because **ViewModels** may contain nested structures:
* Nested **ViewModel Instances** can also be observed
* Changes propagate through the same callback mechanism
* Observation remains consistent regardless of hierarchy depth
This allows complex UI or gameplay state to remain structured and predictable.
## Lifetime and safety
Observation follows the lifetime of the **ViewModel Instance**.
Important rules:
* Do not observe destroyed instances
* Unbind callbacks before destroying instances
* Do not assume callbacks persist after **Artboard** reinitialization
Callbacks are synchronous and not asynchronous events.
## Summary
**ViewModels** are both the input and output boundary of the runtime.
Unreal writes values.\
The **State Machine** evaluates.\
Unreal observes changes.
# Runtime Asset Swapping
Source: https://rive.app/docs/game-runtimes/unreal/runtime-asset-swapping
Swap image assets at runtime in Unreal via data binding.
## Overview
To change a Rive file's images at runtime in Unreal, bind a `UTexture` to a ViewModel image property exposed via data binding in the Rive editor.
> [!WARNING]
>
> The Rive renderer requires image textures to use **premultiplied alpha** (AlphaComposite-style blending). Textures authored with straight alpha can show:
>
> * Dark or black fringes around transparent edges
> * Incorrect compositing against the background
> * Loss of alpha
> * Overly bright / oversaturated images
>
> Export or preprocess textures with premultiplied alpha before using them at runtime.
### Blueprint
Call **Set Image Value** (category *Rive → Data Binding*) on your `RiveViewModel` reference. Enter the image property name (as exposed on the ViewModel via data binding) and pick the source texture from the *In Image* dropdown.

### C++
```cpp theme={null}
#include "Rive/RiveViewModel.h"
// ViewModel is a URiveViewModel*, Texture is any UTexture*
ViewModel->SetImageValue(TEXT("MyImageProperty"), Texture);
```
`SetImageValue` accepts any `UTexture` and notifies the state machine that the bound property changed. The property name must match the image property as exposed on the ViewModel via data binding.
## Troubleshooting
* **Image doesn't update:** confirm the property name matches the ViewModel image property as exposed via data binding, and that your `RiveViewModel` is the one driving the artboard instance on screen.
* **Image looks wrong (dark fringes, incorrect alpha, oversaturation):** verify the source texture uses premultiplied alpha.
# Unreal Engine
Source: https://rive.app/docs/game-runtimes/unreal/unreal
Rive’s Unreal runtime allows you to render and control Rive animations natively inside Unreal Engine. It integrates directly with Unreal’s object system and rendering pipeline and is designed for real-time use cases.
## Supported Unreal versions
* Unreal Engine 5.7.3 and above
## Supported platforms
* Microsoft DirectX 11
* Microsoft DirectX 12
* PC Vulkan
* macOS
* visionOS (experimental)
* PlayStation 5
* Nintendo Switch
* Nintendo Switch 2
* Xbox Series X
* Steam Deck - Proton D3D11
> [!WARNING]
>
> Mobile platform support is planned but not yet available.
## Rendering backends
Depending on platform and engine configuration, supported backends include:
* DirectX (Windows)
* Metal (macOS)
> [!NOTE]
>
> The Unreal runtime uses RHI for rendering backend integration.
Rendering is handled by Rive’s native renderer and coordinated with Unreal’s render thread.
## Feature support
| Feature | Supported |
| - | - |
| Animation playback | ✅ |
| State machines | ✅ |
| ViewModels (data binding) | ✅ |
| Property observation | ✅ |
| Text rendering | ✅ |
| Image assets | ✅ |
| Multiple Artboards per file | ✅ |
| Scripting | ✅ |
| Legacy state machine events | Deprecated |
| Legacy direct inputs | Deprecated |
> [!WARNING]
>
> Legacy state machine events and inputs are deprecated.\
> New integrations should use ViewModels for both input and output.
## Architecture overview
The Unreal runtime is built around three core runtime objects:
* **Rive File** — Unreal asset containing imported Rive data
* **Artboard** — Runtime instance responsible for evaluation and rendering
* **ViewModel** — Typed data boundary between Unreal and Rive logic
The typical data flow is:
Unreal → ViewModel → State Machine → ViewModel → Unreal
State machines consume and modify ViewModel properties. Unreal observes those changes.
## Support & community
If you need help:
* Join the Rive Community: [https://community.rive.app](https://community.rive.app)
# Using Triggers
Source: https://rive.app/docs/game-runtimes/unreal/using-triggers
Using triggers in the Rive plugin.
In the Unreal runtime, "events" are modeled as **ViewModel Trigger Properties**.
Fire and observe triggers through the **ViewModel Instance**.
> [!NOTE]
>
> Use **Trigger Properties** for one-shot actions (clicks, milestones, transitions).
## Recommended flow
1. Define a **Trigger Property** in your Rive ViewModel (for example `OnClick`).
2. In Unreal, create and bind a **ViewModel Instance** to your Rive widget or artboard.
3. Fire the trigger from Blueprint using **Call **.
4. Respond to the trigger in Blueprint using **Bind Event to **.
## Blueprint setup
1. Create a Rive widget from your imported `.riv` file.
2. Create a **ViewModel Instance** using **Make View Model**.
3. Assign that instance to the widget/artboard.
4. Keep a reference to the bound ViewModel instance.
> [!TIP]
>
> Keep ViewModel creation and delegate binding in the same owning Blueprint so lifetime is clear.
## Firing a trigger in Blueprint
When you want to fire an event (button press, gameplay action, etc.), call the trigger function exposed on the bound ViewModel instance.
Typical pattern:
1. Get your bound ViewModel instance reference.
2. Call **Call ** (for example `Call OnClick`).
3. Pass any required inputs for the generated function signature.
The trigger is consumed during the next artboard tick and resets automatically.
In the following image, the trigger "loaded" is being fired from Blueprint:

## Observing trigger results
If Unreal needs to react when the trigger is fired:
* Use **Bind Event to ** on the ViewModel instance.
* Handle callbacks synchronously during the update cycle.
* Unbind delegates before destroying the ViewModel instance.
In the following image, a custom event is bound to the trigger "loaded":

# Performance
Source: https://rive.app/docs/getting-started/best-practices
Editor & runtime performance and usage considerations.
Rive is built to efficiently play interactive graphics in the editor and at runtime in applications and games. However, poorly optimized animations can consume significant resources and cause poor performance, particularly on low-end devices. In the following sections, we will outline important considerations and tips for maintaining optimal performance and minimal resource utilization both during design/animate time in the Rive editor, as well as during runtime in applications.
> [!NOTE]
>
> We recommend continuous testing of your animations on your target devices/platforms.
## Design-time considerations
See below for some techniques to employ in the Rive editor to keep Rive performant:
### Asset optimizations
Image, audio, and font assets are often the biggest source of bloat in .riv files. Unoptimized assets increase download size and must be loaded into memory, which can lead to slowdowns—especially on lower-end devices.
> [!NOTE]
>
> Only assets used in artboards will be compiled for runtime. Items in the Assets panel that aren't used in an artboard will not increase the size of your .riv file.
#### Fonts
Font files often include thousands of glyphs you may not need, such as Greek letters, mathematical operators, and icons. To reduce the size of the exported font or .riv file, [select which glyphs to include](/docs/editor/text/fonts#glyph-%2F-script-selection).
#### Raster image sizes & dimensions
It is crucial to ensure that the size of an image asset is appropriate for its usage. For instance, avoid using an image with large dimensions (e.g., 8192 x 7022) when it will be displayed in a small section of your artboard (e.g., sized 100 x 100).
Using large images can quickly consume device memory. This is particularly true on mobile devices where applications are more memory-constrained. Even if these images are compressed, their dimensions will still impact the amount of application memory used.
If you have a very large image and only part of it will be visible at any given time (ie; a scrolling background), consider breaking the image into smaller chunks or mixing raster and recreating part of it as a vector.

#### Raster image compression
Compression involves reducing the file size by employing various algorithms to discard some image data. You can compress images directly from the Rive editor, which means you maintain the original image but compress the images for runtime use. If the asset is embedded in the animation, this will reduce the file size of the exported riv.
For the smallest image file size and best performance, we recommend exporting assets using the WebP Format.
#### Vector images
Be efficient with the number of vertices in your vector image. While a few extra vertices won’t have much of an impact, thousands might. Be especially careful when importing vectors that were generated with AI, converted from raster images, or were created in drawing apps.
### Layer blend modes for web
Blend modes are particularly expensive on the web because WebGL doesn’t expose mechanisms for accessing the framebuffer. To apply a blend mode, Rive must copy rendered pixels into a separate texture before compositing, which introduces significant performance and memory overhead.
While there are efforts underway to improve this through new WebGL capabilities, these solutions are still pending broader support. Until then, it’s best to use blend modes sparingly in web projects to ensure optimal performance.
### Artboard considerations
#### Clipped Artboards
Clipping artboards is generally fine, but if you're experiencing performance issues, it's worth minimizing their use. Clipping can be computationally expensive, as the renderer must evaluate every object—including component instances—to determine pixel visibility. Instead, consider applying clips to specific objects or groups within the artboard.
In most cases you can safely remove the clip from the main artboard itself, since nothing outside the Rive instance will be rendered at runtime.
#### Artboard export
Not every artboard in your Rive file is included in the exported `.riv`. The default artboard and any artboards marked as **Components** are included automatically. Other artboards, including their animations, State Machines, and other artboard-specific content, are excluded.
Assets referenced by an excluded artboard may still be included in the `.riv`. To exclude an asset from the runtime file, set its export behavior to **Prevent Export**.
### Idle Animations
If you have idle animation states where the graphic remains static at a given state in a state machine, consider using a "one-shot" animation and ensuring that the timeline animation is not unnecessarily long. At runtime in a state machine, if no looping animations or active blend states are playing, most runtimes will preemptively [“pause” themselves](#settling) until a transition to another state. This is useful because resource consumption (i.e., CPU usage) may decrease to the point of making Rive impact on resources negligible in applications.
Scenarios: Icons, buttons, graphics that only animate based on user interaction, etc.
### Using Solos
A [Solo](/docs/editor/manipulating-shapes/solos) is similar to a group but with the added ability to toggle the rendering of nested objects. It functions like a radio button, deactivating other objects on the same level.
When you're looking to show or hide a specific object, using a Solo can be a more efficient since it stops the rendering of any non active objects.
Solos can also be an effective way to build skins for a character, but it's important to note that this should only be used if your skins require binding and weighting.
**Data Binding Artboards**\
When looking to build more complex skins (that don't require binding and weighting), or wanting to swap out widgets, icons, ect... data binding an artboard node is the most performant way to do this.\
\
In addition to only rendering the things you need, you also save yourself both memory and CPU usage by providing only the graphics you need.
### Blend States
Similar to the guidance in “Idle Animations”, ensure blend states transition out to other states, or move to an exit state when finished if possible. When blend states are activated at runtime, Rive will continually play the state machine, even if it is not necessary anymore. Providing some transition away from the blend state when complete ensures Rive has one less “active” animation to track when considering whether to self-pause at any point while playing the state machine.
## Runtime considerations
See below for some techniques to employ when using Rive runtimes in application to keep Rive performant:
### Out-of-band assets
See our documentation on [Loading Assets](/docs/runtimes/loading-assets). This feature allows you to dynamically load and replace assets (such as fonts, images, and audio) at runtime through code and provide the resources to your Rive graphic. This has the following benefits:
* Reduces the exported `.riv` binary size.
* Assets can be reused across multiple Rive files or other areas of your application.
* Assets can be preloaded and cached to be more readily available before displaying a Rive graphic.
* Assets can be swapped based on the users’ screen size and resolution, like in this [web JS example](https://codesandbox.io/p/sandbox/cool-dewdney-hlk5xl?file=%2Fsrc%2Findex.ts).
### Caching your .riv
If you're using the same Rive file in multiple places across your page or app, you can [cache the .riv](/docs/runtimes/caching-a-rive-file) file to improve performance. The key benefit of caching is that the file only needs to be parsed and decoded once. Creating new artboard instances from a cached, already-decoded file is significantly faster than decoding the file each time before instantiating an artboard.
### Deferring decoding
If your `.riv` contains many artboards but you only show a few at a time, you can [defer decoding](/docs/runtimes/deferred-file-loading) so that artboards, animations, and view model instances decode the first time they're used instead of while the file loads. This can shorten loading time, at the cost of a delay the first time each part is used.
### Settling
A state machine settles once it has nothing left to animate. Most runtimes then stop advancing and drawing it, so an idle graphic uses almost no CPU or GPU. This is the self-pausing described in [Idle Animations](#idle-animations) and [Blend States](#blend-states). The table below covers the Flutter, web, React, Apple, Android, React Native, Unity, and Unreal runtimes.
A state machine keeps running while there's still something to animate in any of its layers, or in its artboard, including any [component](/docs/editor/fundamentals/components) that isn't hidden, either by a Solo or inside a [hidden Layout](/docs/editor/layouts/sizing-and-positioning#hiding-a-layout). For example:
* A looping or ping-pong animation is playing.
* A blend state is active.
* A one-shot animation hasn't reached its end.
* A transition is in progress or waiting for its [exit time](/docs/editor/state-machine/transitions#exit-time).
* A [layout animation](/docs/editor/layouts/layout-animation) is in progress.
* A [scroll](/docs/editor/constraints/scroll-constraint) is still moving.
* A [text input](/docs/editor/text/text-input) has focus, so its cursor keeps blinking.
* A script's [`advance`](/docs/scripting/api-reference/interfaces/node#advance) keeps returning `true`.
A settled state machine wakes when the runtime sees a change, such as pointer input on a listener, or a state machine input or view model property set from code.
Settling and drawing are separate. A state machine that hasn't settled advances every frame, but some runtimes skip the draw on frames where nothing in the artboard changed, and keep showing the last drawn frame.
| Runtime | Settling | Skips unchanged draws |
| - | - | - |
| Flutter | Automatic. | Yes by default, from `rive` `0.15.0`. Change it with [`drawOptimization`](/docs/runtimes/flutter/flutter#draw-optimization). |
| Web | Off by default. Turn it on with [`enableSettling`](/docs/runtimes/web/canvas-vs-webgl#settling), added in `v2.52.0`. | Yes by default. Change it with [`drawingOptions`](/docs/runtimes/web/rive-parameters). |
| React | Off by default. Turn it on with [`enableSettling`](/docs/runtimes/react/parameters-and-return-values#parameters) in `useRive`, from `v4.40.0`. | Yes by default. Change it with `drawingOptions`. |
| Apple, New Runtime | Automatic. | Yes. Can't be turned off. |
| Apple, Legacy Runtime | Automatic. Call `play()` after setting a view model property on a settled state machine. See the [migration guide](/docs/runtimes/apple/migrating-from-legacy#updating-a-data-bind-unsettles-the-state-machine). | Yes by default, from `6.14.0`. Change it with `RiveView.drawOptimization`. |
| Android, new runtime | Automatic. | Yes, from `11.17.0`. Can't be turned off. |
| Android, legacy runtime | Automatic. Call `play()` after setting a view model property on a settled state machine. See the [migration guide](/docs/runtimes/android/migrating-from-legacy#updating-a-data-bind-unsettles-the-state-machine). | No. |
| React Native, `@rive-app/react-native` `0.5.0` and later | Automatic. On Android before `0.5.14`, a settled view keeps drawing every frame, and you call [`playIfNeeded()`](/docs/runtimes/react-native/rive-ref-methods) after setting a view model property on a settled state machine. | Yes on iOS. On Android, only with rive-android `11.17.0` or later. See [native version customization](/docs/runtimes/react-native/native-version-customization) for the rive-android version you build with. |
| React Native, `rive-react-native`, or `@rive-app/react-native` `0.4.x` and earlier | Automatic. After setting a view model property on a settled state machine, call `play()` on `rive-react-native`, or `playIfNeeded()` on `@rive-app/react-native`. | Yes on iOS, with rive-ios `6.14.0` or later. No on Android. |
| Unity | Keeps advancing every frame. | Yes by default. Change it with the [Rive Panel](/docs/game-runtimes/unity/components#rive-panel)'s **Draw Optimization**. |
| Unreal | Stops advancing, but keeps drawing every frame. | No. |
### Pausing programmatically
There are several cases where you may want to pause a state machine configured with Rive programmatically. By pausing the Rive graphic at runtime, you may notice that Rive’s impact on the application has negligible resource consumption (i.e., CPU).
1. Rive graphic is offscreen
a. If a Rive graphic is scrolled offscreen and does not need to continue playing, call the `pause` API on the respective runtime you’re using to prevent Rive from continuing to animate and consume resources when not needed.
b. Call the `play` API to continue playing Rive when the graphic needs to continue animating if back onscreen.
2. Accessibility
* If a user has set in device settings that they prefer reduced motion, you may want to read this property at runtime and programmatically either call `pause` or set `autoplay: false` with the Rive runtime to ensure these users have reduced motion when navigating the application. Alternatively, different artboards or state machines can be created and loaded at runtime that function differently.
3. State machine is idle with static graphics
a. `Pause` when the Rive graphic is idling while it waits for a transition in the state machine from user interaction, data resolving, etc. Runtimes that [settle](#settling) do this for you.
### Low-end devices
Rive will try to run performantly across all browsers/devices, but if you can, test how your application performs on resource-constrained devices with your specific Rive graphics running. You may find that for a given screen, Rive files that include heavily-animated graphics might be overkill for what is truly needed and decide to display static Rive graphics (i.e., autoplay: false) or reduce the amount of Rive entities animating at any given point.
A strategy for lower-end devices could be to create an alternative artboard or state machine with reduced usage/motion, that can dynamically be loaded in at runtime when running on older devices.
# Introduction
Source: https://rive.app/docs/getting-started/introduction
Rive is an agent-native 2D and 3D engine for games, apps, and interactive UI. Build with your coding agent through the Rive CLI, or by hand with professional design and animation tools in the Rive Editor. Use Rive as your whole engine, or add it to the products you already have. Open-source runtimes, no royalties or runtime fees.
## Rive at a glance
> [card] [1. Design](/docs/editor/fundamentals/artboards)
>
> Create vector graphics, responsive layouts, and reusable components, or import images, audio, fonts, and other assets from your favorite design tools.
> [card] [2. Animate](/docs/editor/animate-mode/animate-mode-overview)
>
> Bring your designs to life with timelines, keyframes, and smooth interpolation.
> [card] [3. Make Interactive](/docs/editor/state-machine/state-machine)
>
> Build interactive experiences that respond to user input, screen size, scrolling, and application state.
> [card] [4. Control using Data](/docs/editor/data-binding/overview)
>
> Connect animations, text, colors, layouts, and other properties to real-time data.
> [card] [5. Scripting](/docs/scripting/getting-started)
>
> Use scripting to create custom interactions, procedural animation, and behaviors that go beyond the built-in tools.
> [card] [6. Publish Anywhere](/docs/runtimes/getting-started)
>
> Export once and use your interactive graphics across websites, mobile apps, games, videos, and more.
## Quick start
New to Rive? This step-by-step quickstart walks through the core concepts of the editor while building a complete interactive project from start to finish.
[YouTube video player](https://www.youtube.com/embed/u2kThOXc3Ek)
# Add VAT/Tax ID to Your Invoice
Source: https://rive.app/docs/home/account-admin/account-overview/add-vat-tax-id-to-your-invoice
Need a tax invoice with your VAT or Tax ID for your records? Use our form and we'll email you an updated invoice.
[Request a Tax Invoice](https://forms.rive.app/support?utm_medium=support_page)
You'll need:
* Your original Stripe invoice/receipt number
* Invoice date and amount
* Your company's billing address
* Your VAT/Tax ID number
Your tax invoice will be emailed to you immediately.
***
## For future invoices
To have your tax info included automatically on all future receipts, update your billing details in Stripe:
1. Go to [rive.app/account](https://rive.app/account?utm_source=docs\&utm_medium=content)
2. Click "Manage Billing" to open the Stripe Customer Portal
3. Update your customer information with your Tax ID
4. Save changes
All future invoices will include your tax details automatically.
**Questions?** [Contact support](https://forms.rive.app/support?utm_medium=support_page).
# Cancel a Former Employee's Plan
Source: https://rive.app/docs/home/account-admin/account-overview/cancel-a-former-employees-subscription
If an employee left your company but their Rive plan is still billing your card, we can help cancel it. You don't need access to their account.
## What we can do
* ✅ Cancel the plan
* ✅ Remove your payment method from their account
* ✅ Refund recent charges (typically 1-2 months after departure)
## What we cannot do
* ❌ Give you access to their account
* ❌ Transfer their files to your company
* ❌ Change workspace ownership
**Why:** Workspace ownership belongs to the account that created it, not the payment method. Even if your company card paid for it, the workspace is theirs. We don't override ownership without the account holder's consent.
If you need the files, you'll need to work that out directly with the former employee.
***
## How to request cancellation
[Contact support](https://forms.rive.app/support?utm_medium=support_page) with:
* Your company name
* The employee's name and email (if known)
* Last 4 digits of the card being charged
* Approximate date the employee left
We'll verify you control the payment method, cancel the plan, and remove your card. You'll get confirmation within 1-2 business days.
***
## Prevent this next time
Create a company-owned workspace and add employees as members. When someone leaves, you remove them—no plans to chase down, no files lost.
**Questions?** [Contact support](https://forms.rive.app/support?utm_medium=support_page).
# Change Your Email or Password
Source: https://rive.app/docs/home/account-admin/account-overview/change-your-email-or-password
1. Go to [rive.app/account](https://rive.app/account?utm_source=docs\&utm_medium=content)
2. Make sure you're on the **Account** tab
**To change your email:**
* Click "Edit Profile" on the right
* Update your email
* Click "Save changes"
**To change your password:**
* Click "Change Password"
* Enter your new password
* Click "Save Password"
**Questions?** [Contact support](https://forms.rive.app/support?utm_medium=support_page).
# Refunds
Source: https://rive.app/docs/home/account-admin/account-overview/refunds
## Our policy
Per Rive's [Terms of Service](/docs/legal/terms-of-service), fees are non-refundable. If you cancel your plan, you keep access until the end of your current billing period—we just won't renew it.
## Billing errors
If you were charged incorrectly (duplicate charge, charged after cancellation, wrong amount), [contact support](https://forms.rive.app/support?utm_medium=support_page) with:
* Your account email
* Date and amount of the charge
* What went wrong
We'll investigate and fix any legitimate billing errors.
## Before you upgrade
If you're not sure Rive is right for you:
* Use the free plan first to test it out
* Start with monthly instead of annual if you want flexibility
* Double-check you're upgrading the right workspace
**Questions?** [Contact support](https://forms.rive.app/support?utm_medium=support_page).
# HTML Embed
Source: https://rive.app/docs/integrations/html-embed
Embed Rive in platforms that support custom HTML.
Use Rive in any platform that supports custom HTML embeds by pasting the **Embed Code** or **Embed Link** generated from the Rive editor.
This is useful for tools like **WordPress** and other platforms where you can add your own HTML, but a [dedicated Rive integration](/docs/integrations/overview) or [runtime](/docs/runtimes) is not available.
## Generate the embed code
**1. Open the Embed URL dialog**
In the Rive editor, click the **hamburger menu** in the top-left corner and select **Generate Embed URL**.

**2. Generate an embed URL**
In the dialog that appears, click **Generate Embed URL**.

**3. Choose an embed URL type**
Once the URL is generated, select the option that best fits how you plan to use your file.
Some platforms (like Notion) support embedding directly from an **Embed link**. Otherwise, use the iframe **Embed code**.
> [!NOTE]
>
> For more information about the various types of embed URLs, see [Embed URLs](/docs/editor/embed-urls/overview#embed-url-options).

## Add the embed to your platform
**1. Open the page, post, or project where you want to place your Rive file**
**2. Copy the Embed link or Embed code**
**3. Paste into your page, post, or project**
**4. Save or publish your changes**
## Need help?
Support for embeds depends on the platform you are using. For issues with adding custom HTML or iframes, refer to that platform’s documentation or support channels.
# 3rd Party Integrations
Source: https://rive.app/docs/integrations/overview
These integrations are maintained outside of Rive.
For help or support, please refer to the respective tool’s documentation or community.
## Website builders
* **[Framer](https://www.framer.com/marketplace/plugins/rive/)** — Use the official Rive Framer plugin for direct integration
* **[Webflow](https://help.webflow.com/hc/en-us/articles/33961216978451-Embed-Rive-animations)** — Native support for Rive animations
## Video & rendering
* **[Remotion](https://www.remotion.dev/docs/rive/)** — Render Rive animations to video programmatically
* **[Revideo](https://github.com/redotvideo/examples/tree/main/rive-explanation-video)** — Render Rive animations to video programmatically
## HTML embed
Many platforms support custom HTML embeds or link-based embeds (for example, WordPress or Notion).
For these platforms, use the [HTML embed method](/docs/integrations/html-embed).
# .riv File Format
Source: https://rive.app/docs/runtimes/advanced-topic/format
The .riv file is the binary runtime format exported from the Rive Editor and used by all Rive runtimes.
## Runtime format
The Rive editor exports your project as a .riv file for consumption by the Rive runtimes. This is a binary representation of your Artboards, Shapes, Animations, State Machines, etc. This is the file that Rive's runtimes read to display your content in an application, game, website, etc. The format was designed to provide a balance of quick load times, small file sizes, and flexibility with regards to future changes/addition of features.
### Binary types
A binary reader for Rive runtime files needs to be able to read these data types from the stream.
> [!NOTE]
>
> Byte order is little endian.
| Type | Description |
| - | - |
| variable unsigned integer | LEB128 variable encoded unsigned integer (abbreviated to varuint going forward) |
| unsigned integer | 4 byte unsigned integer |
| string | unsigned integer followed by utf-8 encoded byte array of provided length |
| float | 32 bit floating point number encoded in 4 byte IEEE 754 |
> [!NOTE]
>
> Reference Binary Readers
>
> [C++ Reader](https://github.com/rive-app/rive-cpp/blob/master/src/core/binary_reader.cpp) [C++ Decoder](https://github.com/rive-app/rive-cpp/blob/master/include/rive/core/binary_reader.hpp)
### Header
The header is the first thing written into the file and provides basic information for the runtime to verify that it can read this file. A ToC (table of contents/field definition) is provided which allows the runtime to understand how it can skip over properties and objects it may not understand. This is part of what makes the format resilient to future changes/feature additions to the editor. An older runtime can at least attempt to load an older file and display it without the objects and properties it doesn't understand.
| Value | Type |
| - | - |
| Fingerprint | 4 bytes |
| Major Version | varuint |
| Minor Version | varuint |
| File ID | varuint |
| ToC | byte aligned bit array |
**Fingerprint**
The file fingerprint just lets the importer quickly sanity check that it's actually looking at a file exported by Rive. This is 4 bytes representing the utf8/ascii "RIVE". In a hex editor this looks like.
> [!NOTE]
>
> 0x52 0x49 0x56 0x45/"RIVE"
**Major Version**
Runtimes are compatible with only a single major Rive export format version. The current major format is 7. If a runtime that supports format major 7 encounters a format major 6 file, it will immediately error and not attempt to read any further content, as the format is understood to be fundamentally different. This is provided as a last-resort tool for Rive to fundamentally change its export format if needed, and we try very hard to do this as rarely as possible.
The move from format 6 to format 7 happened years ago, and the editor no longer exports format 6 files.
If a future major format is introduced, runtimes and exports must match major format versions. In practice, this means:
* if you update to runtimes that support a new major format, you must re-export files to that major format
* if you stay on older runtimes, you must export files in the older compatible major format
* runtimes that add support for a new file format major version will also ship a major runtime version update
Example: if the Android runtime is currently major version `11`, and support for a new file format major is introduced, Android runtime support for that format will ship in a major `12` release.
To adopt it, you update to Android runtime `12` and re-export files to the new file format major.
If you need to verify a file's format version programmatically, read the `Major Version` and `Minor Version` values from the file header. Rive runtimes also surface a descriptive import error when the file format is incompatible.
> [!NOTE]
>
> Major versions are not cross-compatible. For example, a runtime that supports format version 6 cannot read format version 7 files, and vice versa.
> Whenever a new major file format version is introduced, a corresponding major release is issued for all supported runtimes.
**Minor Version**
Minor version changes are compatible with each other provided the major version is the same. However, certain newer features may not be available if the runtime is of a different minor version. For example, major version 7 introduces the State Machine. We're working on adding new state types to the State Machine. A version 7.0 runtime may not be able to load all the states exported in a 7.1 file. However, the runtime will still be able to play the state machine, it'll simply not be able to do anything when it transitions to states it doesn't understand.
> [!NOTE]
>
> When a file uses newer features that an older compatible runtime does not support, the file still loads and supported features continue to work. Unsupported features are treated as no-ops. Rive runtimes are designed to avoid crashes or undefined behavior for this compatibility scenario.
Example Version Compatibility
| Runtime Version | File Version | Compatibility |
| - | - | - |
| 6.1 | 6.0 | Yes |
| 6.1 | 6.2 | Yes |
| 6.1 | 7.0 | No |
| 7.0 | 6.1 | No |
| 7.0 | 7.1 | Yes |
#### File ID
This is a unique identifier for the file that in the future will be able to be used to distinguish the file by our API. The API isn't defined yet, but some of the planned features include re-exporting a newer version of the file on demand, getting details of the file, etc. For now this can be used to verify which file this export was generated from.
#### ToC
The Table of Contents section of the header is a list of the properties in the file along with their backing type. This allows the runtime to read past properties it wishes to skip or doesn't understand. It does this by providing the backing type for each property ID.
#### Field types
There are 5 fundamental backing types but they are serialized in 4 different ways. Knowing how the type is serialized allows the runtime to know how to read it in. Even if it reads the wrong value or interprets it incorrectly, the important aspect is being able to read past it so the rest of the file can be read in safely.
For example, a boolean can be read as an unsigned integer as the backing type and serializer is compatible. Even though reading the boolean as an integer will not provide the valid value for the property, the runtime can still just read past it.
#### ToC data
The list of known properties is serialized as a sequence of variable unsigned integers with a 0 terminator. A valid property key is distinguished by a non-zero unsigned integer id/key. Following the properties is a bit array which is composed of the read property count / 4 bytes. Every property gets 2 bits to define which backing type deserializer can be used to read past it.
> [!NOTE]
>
> The intention here is to provide the known property type keys and their backing type, such that if the property type is unknown, the reader can read the entirety of the value without under/over running the buffer.
| Backing Type | 2 bit value |
| - | - |
| Uint/Bool | 0 |
| String | 1 |
| Float | 2 |
| Color | 3 |
As an example, if there were a file with three known property types (property 12 a uint value, property 16 a string value, and 6 a bool value) the exporter would serialize data as follows:
varuint: 12
varuint: 16
varuint: 6
varuint: 0
2 bits: 0
2 bits: 1
2 bits: 0
> [!NOTE]
>
> Reference ToC Deserializers [Flutter](https://github.com/rive-app/rive-flutter/blob/bbee63bb6c791dcabd0cd9d9788ca7ec4783fddb/lib/src/rive_core/runtime/runtime_header.dart#L43-L60) [C++](https://github.com/rive-app/rive-cpp/blob/4512406300b7333ba543cd87930e67a24c2fc715/include/runtime_header.hpp#L76-L104)
#### Baseline properties
Rive won't export properties that have been known to the system since the latest major version. We baseline when we shift new major versions as there will be no minor version that needs to read past newer properties. Newly introduced properties after the shift to the latest major will export as they are added and new minor versions are released.
## Content
The rest of the file is simply a list of objects, each containing a list of their properties and values. An object is represented as a varuint type key. It is immediately followed by the list of properties. Properties are terminated with a 0 varuint. If a non 0 value is read, it is expected to be the type key for the property. If the runtime knows the type key, it will know the backing type and how to decode it. The bytes following the type key will be one of the binary types specified earlier. If it is unknown, it can determine from the ToC what the backing type is and read past it.
### Core
All objects and properties are defined in a set of files we call core defs for [Core Definitions](https://github.com/rive-app/rive-cpp/tree/master/dev/defs). These are defined in a series of JSON objects and help Rive generate serialization, deserialization, and animation property code. The C++ and Flutter runtimes both have helpers to read and generate a lot of the boilerplate code for these types.
#### Object
A core object is represented by its Core type key. For example, a Shape has [core type key 3](https://github.com/rive-app/rive-cpp/blob/4512406300b7333ba543cd87930e67a24c2fc715/dev/defs/shapes/shape.json#L4). Similarly you can see the generated code for the C++ runtime also [identifies a Shape with the same key](https://github.com/rive-app/rive-cpp/blob/4512406300b7333ba543cd87930e67a24c2fc715/include/generated/shapes/shape_base.hpp#L12).
#### Properties
Properties are similarly represented by a Core type key. These are unique across all objects, so [property key 13](https://github.com/rive-app/rive-cpp/blob/4512406300b7333ba543cd87930e67a24c2fc715/dev/defs/node.json#L16) will always be the X value of a Node object, and it [matches in the runtime](https://github.com/rive-app/rive-cpp/blob/4512406300b7333ba543cd87930e67a24c2fc715/include/generated/node_base.hpp#L33). A Node's X value is known to be a floating point value so when it is encountered [it will be decoded as such](https://github.com/rive-app/rive-cpp/blob/4512406300b7333ba543cd87930e67a24c2fc715/include/generated/node_base.hpp#L66-L68). Property key 0 is reserved as a null terminator (meaning we are done reading properties for the current object).
### Example serialized object
| Data | Type/Size | Description |
| - | - | - |
| 2 | varuint | object of type 2 (Node) |
| 13 | varuint | X property for the Node |
| 100.0 | 4 byte float | the X value for the Node |
| 14 | varuint | Y property for the Node |
| 22.0 | 4 byte float | the Y value for the Node |
| 0 | varuint | Null terminator. Done reading properties and have completed reading Node. |
### Context
Objects are always provided in context of each other. A Shape will always be provided after an Artboard. The Node's artboard can always be determined by finding the latest read Artboard. This concept is used extensively to provide the context for objects that require it. Another example, a KeyFrame will always be provided after a LinearAnimation, meaning you can always determine which LinearAnimation a KeyFrame belongs to by simply tracking that last read LinearAnimation.
### Hierarchy
Objects inside the Artboard can be parented to other objects in the Artboard. This mapping is more complex and requires identifiers to find the parent. The identifiers are provided as a [core def property](https://github.com/rive-app/rive-cpp/blob/4512406300b7333ba543cd87930e67a24c2fc715/dev/defs/component.json#L28-L38). The value is always an unsigned integer representing the index within the Artboard of the ContainerComponent derived object that makes a valid parent.
> [!NOTE]
>
> For specifics around import context, you can review the ImportStack pattern used in the File reader. [Dart](https://github.com/rive-app/rive-flutter/blob/bbee63bb6c791dcabd0cd9d9788ca7ec4783fddb/lib/src/rive_file.dart#L101) [C++](https://github.com/rive-app/rive-cpp/blob/4512406300b7333ba543cd87930e67a24c2fc715/src/file.cpp#L137)
# Rive Markup Language (RML)
Source: https://rive.app/docs/runtimes/advanced-topic/rml
The XML format that describes a Rive scene as text.
Rive Markup Language (RML) is a text-based representation of a Rive file. It lets you create and modify Rive content as code, making it possible to build Rive files with coding agents and other text-based workflows instead of working exclusively in the Editor.
RML uses XML to describe the objects and relationships in a Rive file. Every element is a Rive type, every attribute is one of its properties, and nesting elements links them together. The names are the same ones the Editor uses, so there is no separate RML object model to learn.
A project can be a single `.rml` file or several. The [Rive CLI](/docs/cli/overview) compiles them together into one `.riv` file for use with the Rive Runtimes, or a `.rev` file that you can open and continue editing in the Rive Editor.
Work with a [coding agent](/docs/cli/agents) to create RML, compile it, inspect the result, and iterate on your Rive file.
## Example
The following example shows how RML maps familiar Rive concepts (an artboard, shapes, fills, an animation, and a State Machine) to XML.
```xml scene.rml theme={null}
```
## How RML maps to Rive
Every document is wrapped in a single `Rive` root. It takes two required attributes: `version`, the RML format version, currently `1`; and `kind`, which is `fragment` for a project file you write yourself. The other value, `bundle`, is the self-contained document the Rive Editor exports, and a project's files are never bundles. `Rive` must be the first and only top-level element, and the CLI refuses a document without it.
Inside that root, RML follows the structure of a Rive file. Artboards contain their scene content, while assets, view models, converters, and enums sit alongside them as root elements.
A fragment never declares a `Backboard`. What the Editor keeps there, such as the default artboard and the publish settings, is project configuration, so it lives in [rive.yaml](/docs/cli/reference/project-config) instead. The build creates the `Backboard` from those keys. Only a bundle carries a `Backboard` element.
Nesting reflects relationships between Rive objects. In the example above, the `Shape` contains a `Triangle` path and a `Fill`. Properties belong to their corresponding Rive type, so the transform position (`x` and `y`) belongs to the `Shape`, while `width` and `height` belong to the `Triangle`.
Animations reference the objects and properties they change. Here, `KeyedObject objectId="0:14"` targets the shape named "Triangle", while `propertyKey="15"` identifies its rotation property. You can write `property="rotation"` instead, and `rive schema Shape --animatable` lists both forms. The State Machine references that animation, and `defaultStateMachineId="0:7"` on the Artboard causes the State Machine to play when the file loads.
## Splitting a project across files
A project can hold any number of `.rml` files, in any folders, and they compile as one
document. Split by whatever reads well, such as artboards in one file and view models
in another. Each file keeps its own `Rive` root with `kind="fragment"`.
Smaller files also mean less for a [coding agent](/docs/cli/agents) to read when it only
needs to change one part of the scene.
```text theme={null}
myproject/
rive.yaml
scene.rml
data/
view_models.rml
```
An id declared in one file can be referenced from another, ids may not repeat across
files, and a problem is reported against the file it is in.
> [!NOTE]
>
> Files compile in path order, and that order decides how artboards land in the `.riv`.
> Name the default artboard with `main` in [rive.yaml](/docs/cli/reference/project-config)
> rather than relying on a filename that sorts first.
Run `rive samples` and pick `rml_split` for a working example.
> [!NOTE]
>
> The following sections use the Rive CLI to look up RML types, compile files, and inspect the results. See [Rive CLI](/docs/cli/overview) to install the CLI and learn the available commands.
## Writing RML
### IDs and references
RML uses IDs when one element needs to reference another. For example, an animation uses `objectId` to identify the object it animates, while an Animation State uses `animationId` to identify the animation it plays.
IDs are two numbers separated by a colon, such as `0:12` or `14:11981`. Each ID must be unique across the entire document. Elements only need an `id` when another element references them.
References use attributes ending in `Id`, such as `styleId`, `animationId`, and `objectId`. Nesting creates many of these relationships automatically, so you usually don't need to write the reference yourself. Run `rive docs format` to see which references are created by nesting.
### Value formats
| Type | Written as |
| - | - |
| Color | ARGB hex, no `#`: `colorValue="FFFF5A3C"`. Six digits is opaque RGB. |
| Boolean | `"true"` / `"false"` |
| Enum | A name or its integer: `layoutWidthScaleType="fill"` |
| Rotation | Radians. A full turn is `6.2831855`. |
| Animation timing | Frames, at the animation's `fps` (default 60). Transition durations are milliseconds. |
## Checking your work
Three checks, and none replaces the others:
```bash theme={null}
rive --verify # does it compile? (RML, Luau and shaders)
rive inspect --json # what got built, and is `problems` empty?
rive --screenshot=out.png # does it look right?
```
A clean build proves that the file compiles, but not that it behaves or looks as intended.
Run `inspect` for what got built, and
a screenshot for what it looks like. A bind pointing at the wrong property, or a
shape that renders invisibly, passes the first two checks. See
[Examples](/docs/cli/examples#headless-rendering).
## RML reference
RML includes hundreds of Rive types and properties. Rather than memorizing or guessing their names, use the CLI to look up the schema:
```bash theme={null}
rive schema Rectangle # properties, defaults, enum names, property keys
rive schema --search gradient # find a type by name
rive schema Shape --animatable # properties that can be keyed
rive schema Shape --bindable # properties that can be data bound
```
For broader RML concepts and patterns, use the RML reference included with the CLI:
```bash theme={null}
rive docs # reference index
rive docs format # RML structure and format
rive docs skeleton # a complete file, annotated line by line
rive docs --list # list available topics
rive docs --search gradient # search all topics
```
The reference covers topics including layout, data binding, State Machines, text, drawing, rigging, transforms, easing, assets, keyboard focus, and accessibility semantics. `rive docs gotchas` covers common issues, including those that may fail silently.
# Android
Source: https://rive.app/docs/runtimes/android/android
The Android runtime for Rive.
Welcome to using Rive on Android. Rive runtime libraries are open-source, with Android available in the [rive-android](https://github.com/rive-app/rive-android) GitHub repository.
> [!WARNING]
>
> Note that certain Rive features may not be supported yet for a particular runtime, or may require using the Rive Renderer.
>
> For more details, refer to the [feature support](/docs/feature-support/) and [choosing a renderer](/docs/runtimes/choose-a-renderer/) pages.
## The two Android APIs
Rive for Android provides two main APIs for integrating Rive into your application.
**The New Compose API (Beta)**
This API is designed for Jetpack Compose, allowing for a more modern and declarative approach to building UIs. It is currently in beta and undergoing additional testing, and some issues may be uncovered during development. We will work to address these quickly as they come up. It is feature complete, production ready, and recommended for any new projects using Compose, while existing projects should migrate when feasible.
The entry point for this API is the `Rive` composable function, which can be used directly within your Compose UI code.
In addition to providing a more idiomatic Compose experience, this API is also powered by a stronger threading model with higher stability and flexibility to spread Rive work across multiple threads.
In the future this threading model will also include a View-based API for projects that cannot use Compose.
**The Legacy View-based API**
This API is based on Android Views and XML layouts. It has been widely deployed in production applications. It also supports [Compose by using AndroidView](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/LegacyComposeActivity.kt), though it does require some boilerplate to set up.
The entry point for this API is the `RiveAnimationView`, which can be added to your XML layouts or instantiated programmatically.
We refer to this as the "legacy" API as we are focusing our development efforts on the new Compose API going forward, though this API will continue to be supported and maintained for some time. For all new development projects, we recommend using the new Compose API. Additionally, we recommend migrating existing projects to the new API when feasible, as this version will be deprecated in the future and will have limited to no new feature development.
## Sample App
To explore the Android API, you can run our Android sample app. Each activity demonstrates a particular feature of the Rive Android runtime.
```bash theme={null}
git clone https://github.com/rive-app/rive-android
```
Open the cloned folder in Android Studio and select the `app` configuration and target device. Ensure that the build variant is set to `preview (default)` by opening the menu `Build - Select Build Variant...` and selecting the `preview (default)` variant for `app`.
The other build variants are for development purposes and require additional configuration. See [CONTRIBUTING.MD](https://github.com/rive-app/rive-android/blob/master/CONTRIBUTING.md).
## Getting Started
If you are looking for getting started instructions for the Legacy API, see [Getting Started (Legacy API)](/docs/runtimes/android/legacy-getting-started).
### Adding Rive to your project
**1. Add the Rive dependency**
Add the following dependencies to your `build.gradle` file in your project. We recommend using the latest version of the Rive Android runtime, which can be found on [Maven Central](https://central.sonatype.com/artifact/app.rive/rive-android).
```groovy theme={null}
dependencies {
...
implementation 'app.rive:rive-android:11.17.0'
// For initialization, you may want to add a dependency on Jetpack Startup
implementation "androidx.startup:startup-runtime:1.1.1"
}
```
**2. Initializing Rive**
Rive needs to link and initialize its C++ runtime for its Kotlin bindings to work.
This can be done via an [initializer](https://developer.android.com/topic/libraries/app-startup) which does this automatically at app startup time. The initialization provider can be set up directly in your app's manifest file.
```xml theme={null}
```
Otherwise this can be achieved by calling the initializer in your code.
```kotlin theme={null}
AppInitializer.getInstance(applicationContext)
.initializeComponent(RiveInitializer::class.java)
```
If you want to initialize Rive yourself, this can be done in code using the following. This is the most flexible option, as you can lazily load the native library, but be sure to call it before any Rive functionality is used.
```kotlin theme={null}
Rive.init(context)
```
**3. Add Rive to your layout**
You can now add `Rive` composables to your Compose layouts. See the following sections for details. If you are using the legacy API, see [Getting Started (Legacy API)](/docs/runtimes/android/legacy-getting-started) instead.
### Enabling logging
The Compose API uses extensive logging, especially at the debug level, to help diagnose issues. By default there is no logger enabled. Most commonly you will want to set the global logger to pipe to Android's Logcat, which has a convenience function as follows. This could be done in your activity's `onCreate` method or in your `Application` subclass, for instance, before any Rive functionality is used.
```kotlin theme={null}
RiveLog.logger = RiveLog.LogcatLogger()
```
### Adding Rive to your composition
**1. Creating a Worker**
The Compose API uses an explicit Rive worker which owns a thread for Rive operations, including file and asset decoding, advancing, and drawing. Before you can use any of the API surface, you must create a worker to host these operations. Be aware that the worker must live for the duration of all Rive resources made from it.
The simplest API within a Compose context is `rememberRiveWorker`, which will create and remember a worker for the lifetime of the composition. However, if you want to handle any unexpected errors during worker creation, you can use `rememberRiveWorkerOrNull`, which will return `null` if the worker could not be created and forward the error to an error state you provide.
```kotlin theme={null}
setContent {
// Simple
val riveWorker = rememberRiveWorker()
// Safe
val errorState = remember { mutableStateOf(null) }
val riveWorker = rememberRiveWorkerOrNull(errorState)
if (riveWorker == null) {
// Handle the error and early return
return@setContent
}
}
```
To render 3D or shader content, create the worker with GPU Canvas enabled. See [GPU Canvas](/docs/runtimes/android/gpu-canvas).
> [!NOTE]
>
> If the GPU driver resets or fails, the worker can lose its render context and stop rendering. Your app should handle this case. See [Handling a lost render context](/docs/runtimes/android/handling-render-context-loss).
**2. Loading a Rive File**
Before you can display a Rive element, you must load a Rive file, i.e. an exported .riv file. Rive files are specified by a `RiveFileSource`, which can be either a `RawRes` (for local raw resources) or a `Bytes` (for raw byte data, from any source including the network). In this case, we'll use a raw resource for simplicity. That source, along with the above worker, are passed to `rememberRiveFile`, which internally will load and cache the file for use in the composition.
```kotlin theme={null}
setContent {
... // riveWorker from above
val riveFile = rememberRiveFile(
RiveFileSource.RawRes.from(R.raw.my_rive_file),
riveWorker
)
}
```
The returned value is a `Result`, which can be either `Loading`, `Success`, or `Error`. This pattern requires you to handle the loading and error states appropriately in your UI. Typically this is done with a `when` statement.
```kotlin theme={null}
when (riveFile) {
is Result.Loading -> LoadingIndicator()
is Result.Error -> /* Handle error */
is Result.Success -> {
// The `RiveFile` is held in the `value` property
val file = riveFile.value
// Use the file - see next step
}
}
```
**3. Using the Rive Composable**
With the loaded `RiveFile` you can now display it using the `Rive` composable. The worker is captured in the Rive file, so those two components are all that are needed. Without specifying further, this will choose the default artboard and state machine, as specified in the Rive editor. Further options are explored in the other documentation sections, such as [Artboards](/docs/runtimes/artboards), [State Machines](/docs/runtimes/state-machines), and [Data Binding](/docs/runtimes/data-binding).
```kotlin theme={null}
when (riveFile) {
...
is Result.Success -> {
Rive(riveFile.value)
}
}
```
## Resources
[GitHub](https://github.com/rive-app/rive-android)
[Examples](https://github.com/rive-app/rive-android/tree/master/app/src/main/java/app/rive/runtime/example)
# API Reference
Source: https://rive.app/docs/runtimes/android/api-reference
# Artboards
Source: https://rive.app/docs/runtimes/android/artboards
Selecting which artboard to render at runtime
For more information on creating artboards in the Rive editor, please refer to [Artboards](/docs/editor/fundamentals/artboards).
## Choosing an Artboard
When a Rive object is instantiated or when a Rive file is rendered, you can specify the artboard to use. If no artboard is given, the [default artboard](/docs/editor/fundamentals/artboards#default-state-machine), as set in the Rive editor, is used. If no default artboard is set, the first artboard is used.
Only one artboard can be rendered at a time.
> [tab] Compose
>
> By default, the `Rive` composable will select and create the default artboard specified in the Rive editor. To specify a different artboard, you must first create an `Artboard` object from a loaded `RiveFile`.
>
> ### Compose
>
> Artboard objects can be created in Compose using the `rememberArtboard` function, which takes a Rive file and name of the artboard.
>
> ```kotlin theme={null}
> val artboard = rememberArtboard(myRiveFile, "My Artboard")
> ```
>
> ### Outside of Compose
>
> Alternatively, you can create an artboard outside of Compose contexts. Note that with this approach you are responsible for managing the artboard's lifecycle and must eventually close it with `Artboard::close()` when no longer needed, or leveraging its [`AutoClosable`](https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-auto-closeable.html) interface with a `use` block.
>
> ```kotlin theme={null}
> val artboard = Artboard.fromFile(myRiveFile, "My Artboard")
> ...
> artboard.close()
> ```
>
> ### Using the Artboard
>
> Once you have an artboard, you can pass it to the `Rive` composable via the `artboard` parameter.
>
> ```kotlin theme={null}
> setContent {
> Rive(
> myRiveFile,
> artboard = artboard
> )
> }
> ```
> [tab] Legacy
>
> ### Using XML Layouts
>
> ```xml theme={null}
> app:riveResource="@raw/my_rive_file"
> app:riveArtboard="My Artboard"
> app:riveAutoPlay="true" />
> ```
>
> ### Using Kotlin
>
> ```kotlin theme={null}
> animationView.setRiveResource(
> R.raw.my_rive_file,
> artboardName = "My Artboard",
> autoplay = true
> )
> ```
# Caching a Rive File
Source: https://rive.app/docs/runtimes/android/caching-a-rive-file
Under most circumstances a `.riv` file should load quickly and managing the `RiveFile` yourself is not necessary. But if you intend to use the same `.riv` file in multiple parts of your application, or even on the same screen, it might be advantageous to load the file once and keep it in memory.
## Example usage
To cache a rive file in Android, you can use the Rive `File` class to load and cache the file. That `RiveFile` can then be reused across multiple `RiveAnimationView` instances. Here's a basic example:
```kotlin theme={null}
import app.rive.runtime.kotlin.RiveAnimationView
import app.rive.runtime.kotlin.RiveInitializer
import app.rive.runtime.kotlin.core.File
class MainActivity : ComponentActivity() {
var riveFile: File? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
// Initialize Rive.
AppInitializer.getInstance(applicationContext)
.initializeComponent(RiveInitializer::class.java)
// Load Rive file from assets and cache.
application.assets.open("rewards_demo.riv").use { inputStream ->
val fileBytes = inputStream.readBytes()
riveFile = File(fileBytes)
}
setContent {
Row {
// First cached file usage.
AndroidView(
modifier = Modifier.weight(1f),
factory = { context ->
RiveAnimationView(context).also {
it.setRiveFile(
file = riveFile!!,
stateMachineName = "State Machine 1",
autoBind = true,
)
}
}
)
// Second cached file usage.
AndroidView(
modifier = Modifier.weight(1f),
factory = { context ->
RiveAnimationView(context).also {
it.setRiveFile(
file = riveFile!!,
stateMachineName = "State Machine 1",
autoBind = true,
)
}
}
)
}
}
}
override fun onDestroy() {
riveFile?.release()
super.onDestroy()
}
}
```
Please bear in mind that this is only one way to load the bytes, and your implementation may vary based on your app's architecture. The key point is to create a Rive `File` from the byte array and then set it on the `RiveAnimationView`.
> [!WARNING]
>
> A Rive `File` is reference counted and when created has a reference count of 1. Assigning it to a `RiveAnimationView` will keep an additional reference, but there is still the original reference from its creation. You are responsible for releasing that reference when you are done with the file by calling `File::release`. If you do not release the file, the native memory will remain until the app is closed, even if the Kotlin object is garbage collected.
# Data Binding
Source: https://rive.app/docs/runtimes/android/data-binding
Connect your code to bound editor elements using View Models
Before engaging with the runtime data binding APIs, it is important to familiarize yourself with the core concepts presented in the [Overview](/docs/editor/data-binding/overview).
# View Models
View models describe a set of properties, but cannot themselves be used to get or set values - that is the role of [view model instances](#view-model-instances).
To begin, we need to get a reference to a particular view model. This can be done either by index, by name, or the default for a given artboard, and is done from the Rive file. The default option refers to the view model assigned to an artboard by the dropdown in the editor.
> [tab] Compose
>
> Unlike other runtimes, view models do not exist as a separate object in the Compose API. Instead, they are represented as a `ViewModelSource` sealed class that forms half of a builder pattern used to create view model instances. See [View Model Instances](#view-model-instances) for details on the other half - creating instances.
>
> ```kotlin theme={null}
> // Named source
> val vmSource = ViewModelSource.Named("My View Model")
> // Default for artboard source
> val vmSource = ViewModelSource.DefaultForArtboard(artboard)
> ```
> [tab] Legacy
>
> ```kotlin theme={null}
> // `view` of type RiveAnimationView
> view.setRiveResource(R.raw.my_rive_file)
> val file = view.controller.file!!
>
> // Get reference by name
> val vm = file.getViewModelByName("My View Model")
>
> // Get reference by index
> for (i in 0 until file.viewModelCount) {
> val indexedVM = file.getViewModelByIndex(i)
> }
>
> // Get reference to the default view model
> val defaultVM = file.defaultViewModelForArtboard(view.controller.activeArtboard!!)
> ```
# View Model Instances
Once we have a reference to a view model, it can be used to create an instance. When creating an instance, you have four options:
1. Create a blank instance - Fill the properties of the created instance with default values as follows:
| Type | Value |
| - | - |
| Number | 0 |
| String | Empty string |
| Boolean | False |
| Color | 0xFF000000 |
| Trigger | Untriggered |
| Enum | The first value |
| Image | No image |
| Font | No font |
| Artboard | No artboard |
| List | Empty list |
| Nested view model | Null |
2. Create the default instance - Use the instance labelled "Default" in the editor. Usually this is the one a designer intends as the primary one to be used at runtime.
3. Create by index - Using the order returned when iterating over all available instances. Useful when creating multiple instances by iteration.
4. Create by name - Use the editor's instance name. Useful when creating a specific instance.
> [!NOTE]
>
> In some samples, due to the wordiness of "view model instance", we use the abbreviation "VMI", as well as "VM" for "view model".
> [tab] Compose
>
> See [View Models](#view-models) for how to get a `ViewModelSource` to use below. With that, you can use the builder pattern to create a `ViewModelInstanceSource`, the second half. That source can then be passed to `rememberViewModelInstance` to create and remember the instance for the lifetime of the composition.
>
> ```kotlin theme={null}
> // From previous section
> val vmSource = ViewModelSource.Named("My View Model")
>
> // Blank instance source
> val vmiSourceBlank = ViewModelInstanceSource.Blank(vmSource)
> // or
> val vmiSourceBlank = vmSource.blankInstance()
>
> // Default instance source
> val vmiSourceDefault = ViewModelInstanceSource.Default(vmSource)
> // or
> val vmiSourceDefault = vmSource.defaultInstance()
>
> // Named instance source
> val vmiSourceNamed = ViewModelInstanceSource.Named(vmSource, "My Instance")
> // or
> val vmiSourceNamed = vmSource.namedInstance("My Instance")
>
> // The completed source can now be used along with the Rive file to create and remember the instance
> val viewModelInstance = rememberViewModelInstance(riveFile, vmiSourceNamed)
> ```
>
> Additionally, you can reference a nested view model instance from within a parent instance using the `Reference` variant.
>
> ```kotlin theme={null}
> val myVMI = rememberViewModelInstance(riveFile, mySource)
> val referenceSource = ViewModelInstanceSource.Reference(myVMI, "Path/To/Nested VMI")
> val nestedVMI = rememberViewModelInstance(riveFile, referenceSource)
> ```
> [tab] Legacy
>
> ```kotlin theme={null}
> val vm = view.controller.file?.getViewModelByName("My View Model")!!
>
> // Create blank
> val vmiBlank = vm.createBlankInstance()
>
> // Create default
> val vmiDefault = vm.createDefaultInstance()
>
> // Create by index
> for (i in 0 until vm.instanceCount) {
> val vmiIndexed = vm.createInstanceFromIndex(i)
> }
>
> // Create by name
> val vmiNamed = vm.createInstanceFromName("My Instance")
> ```
### Binding
The created instance can then be assigned to a state machine or artboard. This establishes the bindings set up at edit time.
It is preferred to assign to a state machine, as this will automatically apply the instance to the artboard as well. Only assign to an artboard if you are not using a state machine, i.e. your file is static or uses linear animations.
> [!NOTE]
>
> The initial values of the instance are not applied to their bound elements until the state machine or artboard advances.
> [tab] Compose
>
> See the [Compose data binding example](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/ComposeDataBindingActivity.kt).
>
> Binding to the state machine happens automatically when the `ViewModelInstance` is passed to the `Rive` composable.
>
> ```kotlin {6} theme={null}
> val vmiSource = ViewModelSource.Named("My View Model").namedInstance("My Instance")
> val vmi = rememberViewModelInstance(riveFile, vmiSource)
>
> Rive(
> riveFile,
> viewModelInstance = vmi
> )
> ```
> [tab] Legacy
>
> See the [Legacy data binding example](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/LegacyDataBindingActivity.kt).
>
> ```kotlin theme={null}
> view.setRiveResource(
> R.raw.my_rive_file,
> artboardName = "My Artboard",
> )
>
> val vm = view.controller.file?.getViewModelByName("My View Model")!!
> val vmi = vm.createInstanceFromName("My Instance")
>
> // Apply the instance to the state machine (preferred)
> view.controller.stateMachines.first().viewModelInstance = vmi
>
> // Alternatively, apply the instance to the artboard
> view.controller.activeArtboard?.viewModelInstance = vmi
> ```
### Auto-Binding
Alternatively, you may prefer to use auto-binding. This will automatically bind the default view model of the artboard using the default instance to both the state machine and the artboard. The default view model is the one selected on the artboard in the editor dropdown. The default instance is the one marked "Default" in the editor.
> [tab] Compose
>
> Auto-binding does not exist in the Compose API due to the nature of composables. Since they are functions, it is difficult to get values out of them as compared to classes. Callbacks would require a null placeholder to remember the value before it has fired which creates more overhead than supplying the instance directly.
>
> The equivalent is to create a view model instance with no source. This will internally create the default artboard, the default view model for that artboard, and the default instance for that view model. You can then pass that into the `Rive` composable.
>
> ```kotlin theme={null}
> val vmi = rememberViewModelInstance(riveFile)
> Rive(
> riveFile,
> viewModelInstance = vmi,
> )
> ```
> [tab] Legacy
>
> ```kotlin {3} theme={null}
> view.setRiveResource(
> R.raw.my_rive_file,
> autoBind = true,
> )
> ```
# Properties
A property is a value that can be read, set, or observed on a view model instance. Properties can be of the following types:
| Type | Supported |
| - | - |
| Floating point numbers | ✅ |
| Booleans | ✅ |
| Triggers | ✅ |
| Strings | ✅ |
| Enumerations | ✅ |
| Colors | ✅ |
| Nested View Models | ✅ |
| Lists | ✅ |
| Images | ✅ |
| Artboards | ✅ |
For more information on version compatibility, see the [Feature Support](/docs/feature-support) page.
### Listing properties
Property descriptors can be inspected on a view model to discover at runtime which are available. These are not the mutable properties themselves though - once again those are on instances. These descriptors have a type and name.
> [tab] Compose
>
> Getting view model properties is a suspend operation, so it needs to be called from a coroutine scope such as `LaunchedEffect`.
>
> ```kotlin theme={null}
> LaunchedEffect(riveFile) {
> riveFile.getViewModelProperties("My View Model").forEach { property ->
> Log.d("My Tag", "Property Name: ${property.name}, Type: ${property.type}")
> }
> }
> ```
> [tab] Legacy
>
> ```kotlin theme={null}
> val vm = view.controller.file?.getViewModelByName("My View Model")!!
>
> // A list of properties
> val properties = vm.properties
> assertContains(
> properties,
> ViewModel.Property(ViewModel.PropertyDataType.NUMBER, "My Number Property")
> )
> ```
### Reading and writing properties
References to these properties can be retrieved by name or path.
Some properties are mutable and have getters, setters, and observer operations for their values. Getting or observing the value will retrieve the latest value set on that property's binding, as of the last state machine or artboard advance. Setting the value will update the value and all of its bound elements.
> [!NOTE]
>
> After setting a property's value, the changes will not apply to their bound elements until the state machine or artboard advances.
> [tab] Compose
>
> ### Writing Values
>
> The Compose API does not have explicit property objects. Instead, property values are set on the `ViewModelInstance` directly using methods which take their path.
>
> ```kotlin theme={null}
> val vmi = rememberViewModelInstance(...)
> vmi.setNumberProperty("Path/To/Property", 10f)
> ```
>
> ### Reading Values
>
> Values are read throw a Kotlin [`Flow`](https://kotlinlang.org/docs/flow.html) which emits the latest value whenever it changes. You can collect this flow in a `LaunchedEffect` or convert it to a `State` using `collectAsState()` (or use `collectAsStateWithLifecycle()` to only collect during certain lifecycle states).
>
> To get the latest value once without observing, you can use the terminal `first()` operator.
>
> ```kotlin theme={null}
> val vmi = rememberViewModelInstance(...)
> // Collect as State
> val numberValue by vmi.numberPropertyFlow("Path/To/Property").collectAsState(initial = 0f)
>
> Text(text = "Number value: $numberValue")
>
> // Or collect
> LaunchedEffect(vmi) {
> vmi.numberPropertyFlow("Path/To/Property").collect { value ->
> Log.d("Rive", "Number value changed: $value")
> }
>
> // Or get once
> val numberValue = vmi.numberPropertyFlow("Path/To/Property").first()
> Log.d("Rive", "Current number value: $numberValue")
> }
> ```
> [tab] Legacy
>
> ```kotlin theme={null}
> val vm = view.controller.file?.getViewModelByName("My View Model")!!
> val vmi = vm.createInstanceFromName("My Instance")
>
> val numberProperty = vmi.getNumberProperty("My Number Property")
> // Get
> val numberValue = numberProperty.value
> // Set
> numberProperty.value = 10f
> ```
### Nested property paths
View models can have properties of type view model, allowing for arbitrary nesting. You can chain property calls on each instance starting from the root until you get to the property of interest. Alternatively, you can do this through a path parameter, which is similar to a URI in that it is a forward slash delimited list of property names ending in the name of the property of interest.
> [tab] Compose
>
> ```kotlin theme={null}
> val parent = rememberViewModelInstance(riveFile, ViewModelSource.Named("Parent VM").namedInstance("Parent"))
>
> // Using references
> val child = rememberViewModelInstance(riveFile, ViewModelInstanceSource.Reference(parent, "Child"))
> val nestedNumber = child.numberPropertyFlow("My Nested Number").collectAsState(0f)
>
> // Or using paths
> val nestedNumber = parent.numberPropertyFlow("Child/My Nested Number").collectAsState(0f)
> ```
> [tab] Legacy
>
> ```kotlin theme={null}
> val vm = view.controller.file?.getViewModelByName("My View Model")!!
> val vmi = vm.createInstanceFromName("My Instance")
>
> val nestedNumberByChain = vmi
> .getInstanceProperty("My Nested View Model")
> .getInstanceProperty("My Second Nested VM")
> .getNumberProperty("My Nested Number")
>
> val nestedNumberByPath = vmi
> .getNumberProperty("My Nested View Model/My Second Nested VM/My Nested Number")
> ```
### Observability
You can observe changes over time to property values, either by using listeners or a platform equivalent method. Once observed, you will be notified when the property changes are applied by a state machine advance, whether that is a new value that has been explicitly set or if the value was updated as a result of a binding.
> [tab] Compose
>
> Observability is the default behavior when using the Compose API with Kotlin Flows. When you collect a property's flow, you will receive updates whenever the property's value changes.
>
> ```kotlin theme={null}
> val vmi = rememberViewModelInstance(...)
> val numberPropertyFlow = vmi.numberPropertyFlow("My Number Property").collectAsState(0f)
> ```
> [tab] Legacy
>
> ```kotlin theme={null}
> val vm = view.controller.file?.getViewModelByName("My View Model")!!
> val vmi = vm.createInstanceFromName("My Instance")
>
> val numberProperty = vmi.getNumberProperty("My Number Property")
> // Observe
> lifecycleScope.launch {
> numberProperty.valueFlow.collect { value ->
> Log.i("MyActivity", "Value: $value")
> }
> }
> // Or collect in Compose
> val numberValue by numberProperty.valueFlow.collectAsState(0f) // 0 as the initial value while waiting for the first value
> ```
### Images
Image properties let you set and replace raster images at runtime, with each instance of the image managed independently. For example, you could build an avatar creator and dynamically update features — like swapping out a hat — by setting a view model's image property.
> [tab] Compose
>
> See the [Compose data binding images example](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/ComposeImageBindingActivity.kt).
>
> To set an image property, you need an `ImageAsset`, which can be created from `rememberImage` using a byte array. The below example loads from raw resources into a `Result` for convenience, but you should use the pattern most appropriate for your app.
>
> ```kotlin theme={null}
> val imageBytes by produceState>(Result.Loading) {
> value = withContext(Dispatchers.IO) {
> context.resources.openRawResource(R.raw.my_image)
> .use { Result.Success(it.readBytes()) }
> }
> }
>
> // `andThen` maps over the Result to only call the lambda if it's a Success, propagating Failure and Loading otherwise.
> val image = imageBytes.andThen { bytes ->
> rememberImage(riveWorker, bytes)
> }
>
> // Or combine into one statement
> val image = produceState>(Result.Loading) {
> value = withContext(Dispatchers.IO) {
> context.resources.openRawResource(R.raw.my_image)
> .use { Result.Success(it.readBytes()) }
> }
> }.value.andThen { bytes ->
> rememberImage(riveWorker, bytes)
> }
>
> val vmi = rememberViewModelInstance(riveFile, ViewModelSource.Named("My View Model").defaultInstance())
> LaunchedEffect(vmi, image) {
> when(image) {
> is Result.Failure -> { /* Handle failure to load image */ }
> is Result.Loading -> { /* Handle loading state if needed */ }
> is Result.Success -> {
> // Set the image property value
> vmi.setImage("Image property", image.value)
> }
> }
> }
> ```
>
> If you want to gate the presentation of your Rive content until the image is loaded and only if both are successful, you can use the `zip` convenience function to combine multiple `Result` objects together.
>
> ```kotlin theme={null}
> val fileAndImage = riveFile.zip(image)
>
> when (fileAndImage) {
> is Result.Failure -> { /* Handle failure to load file or image */ }
> is Result.Loading -> { /* Handle loading state if needed */ }
> is Result.Success -> {
> val (riveFile, image) = fileAndImage.value
> // Both riveFile and image are loaded successfully here
> // You can now present your Rive content and set the image property
> }
> }
> ```
>
> For more information on image assets, see [Loading Assets](/docs/runtimes/android/loading-assets).
> [tab] Legacy
>
> ```kotlin theme={null}
> // Load image from the assets folder.
> val imageBytes = context.resources.openRawResource(R.raw.my_image).use { stream ->
> stream.readBytes()
> }
>
> val vmi = it.stateMachines.first().viewModelInstance!!
>
> // Replace image property in view model instance with new image.
> val riveImage = RiveRenderImage.fromEncoded(imageBytes)
> vmi.getImageProperty("Image property").set(riveImage)
> ```
### Lists
List properties let you manage a dynamic set of view model instances at runtime. For example, you can build a to-do app where users can add and remove tasks in a scrollable Layout.
See the [Editor section](/docs/editor/data-binding/lists) on creating data bound lists.
A single list property can include different view model types, with each view model tied to its own Component, making it easy to populate a list with a variety of Component instances.
With list properties, you can:
* Add a new view model instance (optionally at an index)
* Remove an existing view model instance (optionally by index)
* Swap two view model instances by index
* Get the size of a list
For more information on list properties, see the [Data Binding List Property](/docs/editor/data-binding/lists#view-model-list-property) editor documentation.
> [tab] Compose
>
> See the [Compose data binding lists example](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/ComposeListActivity.kt).
>
> ```kotlin theme={null}
> val mainVMI = rememberViewModelInstance(riveFile)
> val newListItem = rememberViewModelInstance(riveFile, ViewModelSource.Named("My Item VM").namedInstance("My List Item"))
> LaunchedEffect(mainVMI, newListItem) {
> val listProperty = "My List"
>
> // Add new item to the end of the list
> mainVMI.appendToList(listProperty, newListItem)
> // Insert new item at index 0
> mainVMI.insertToListAtIndex(listProperty, 0, newListItem)
>
> // Swap items at index 0 and 1
> mainVMI.swapListItems(listProperty, 0, 1)
>
> // Remove specific instance
> mainVMI.removeFromList(listProperty, newListItem)
> // Remove item at index 0
> mainVMI.removeFromListAtIndex(listProperty, 0)
> }
> ```
>
> Due to the dynamic nature of lists, you may need to create items within a coroutine rather than ahead of time with `rememberViewModelInstance`. Be aware that adding the same instance multiple times to a list will cause them all to share state, which may not be the desired behavior. Use the following pattern to create new instances as needed.
>
> ```kotlin theme={null}
> val mainVMI = rememberViewModelInstance(riveFile)
> LaunchedEffect(mainVMI) {
> val listProperty = "My List"
> // ⚠️ This must be `close`d, which is done here through `AutoCloseable.use`.
> ViewModelInstance.fromFile(
> riveFile,
> ViewModelSource.Named("My Item VM").defaultInstance()
> ).use { item ->
> mainVMI.insertToListAtIndex(listProperty, 0, item)
> }
> }
> ```
> [tab] Legacy
>
> ```kotlin theme={null}
> // Acquire the default view model instance and the list property.
> val vmi = animationView.file!!.firstArtboard.viewModelInstance!!
> val listProperty = vmi.getListProperty("list")
>
> // Create a view model instance for "First" and "Second" and add them to the list.
> val firstInstance = animationView.file!!.getViewModelByName("My Item VM").createInstanceFromName("First")
> listProperty.add(firstInstance)
>
> val secondInstance = animationView.file!!.getViewModelByName("My Item VM").createInstanceFromName("Second")
> listProperty.add(secondInstance)
>
> // Swap the two items in the list.
> listProperty.swap(0, 1)
>
> // Remove both items from the list.
> listProperty.remove(firstInstance)
> listProperty.removeAt(0)
> ```
### Artboards
Artboard properties allows you to swap out entire components at runtime. This is useful for creating modular components that can be reused across different designs or applications, for example:
* Creating a skinning system that supports a large number of variations, such as a character creator where you can swap out different body parts, clothing, and accessories.
* Creating a complex scene that is a composition of various artboards loaded from various different Rive files (drawn to a single canvas/texture/widget).
* Reducing the size (complexity) of a single Rive file by breaking it up into smaller components that can be loaded on demand and swapped in and out as needed.
> [tab] Compose
>
> See the [Compose data binding artboards example](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/ComposeArtboardBindingActivity.kt).
>
> ```kotlin theme={null}
> val vmi = rememberViewModelInstance(mainFile)
> val artboard = rememberArtboard(mainFile, "My Artboard")
>
> LaunchedEffect(vmi, artboard) {
> vmi.setArtboard("My Artboard Property", artboard)
> }
> ```
> [tab] Legacy
>
> ```kotlin theme={null}
> // Acquire the default view model instance and the artboard property.
> val vmi = animationView.file!!.firstArtboard.viewModelInstance!!
> val artboardProperty = vmi.getArtboardProperty("My Artboard Property")
>
> // Set artboard from same file.
> val localArtboard = animationView.file!!.getArtboard("My Artboard")
> artboardProperty.set(localArtboard)
>
> // Load external file if needed
> val externalFile = File.load(context.assets, "external_file.riv")
>
> // Set artboard from external file.
> val externalArtboard = externalFile.getArtboard("My External Artboard")
> artboardProperty.set(externalArtboard)
>
> // Clean up external file when done
> externalFile.dispose()
> ```
>
> You can also create a bindable artboard with a view model instance to control its state.
>
> ```kotlin theme={null}
> // Create the view model instance for the child artboard.
> val childVmi = childFile.getViewModelByName("ChildVM").createBlankInstance()
> val bindableArtboard = childFile.createBindableArtboardByName("Child", childVmi)
>
> // Get the artboard property from the main artboard.
> val vmi = rive.file!!.firstArtboard.viewModelInstance!!
> val artboardProperty = vmi.getArtboardProperty("Artboard property")
>
> // Set the bound artboard VMIs state.
> childVmi.getNumberProperty("rotation").value = 90f
>
> // Set the bound artboard on the main artboard.
> artboardProperty.set(bindableArtboard)
>
> // Release the reference we hold from creation.
> bindableArtboard.release()
> ```
### Enums
Enums properties come in two flavors: system and user-defined. In practice, you will not need to worry about the distinction, but just be aware that system enums are available in any Rive file that binds to an editor-defined enum set, representing options from the editor's dropdowns, where user-defined enums are those defined by a designer in the editor.
Enums are string typed. The Rive file contains a list of enums. Each enum in turn has a name and a list of strings.
> [tab] Compose
>
> ```kotlin theme={null}
> LaunchedEffect(riveFile) {
> val enums = riveFile.getEnums()
> Log.i("RiveEnums", "First enum name: ${enums[0].name}")
> }
> ```
> [tab] Legacy
>
> ```kotlin theme={null}
> val enums = view.controller.file?.enums!!
>
> val firstEnumName = enums[0].name
> val firstEnumFirstValue = enums[0].values[0]
> ```
## Examples
> [tab] Compose
>
> See the following examples:
>
> * [Data Binding Overview](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/ComposeDataBindingActivity.kt)
> * [Data Binding Images](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/ComposeImageBindingActivity.kt)
> * [Data Binding Artboards](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/ComposeArtboardBindingActivity.kt)
> * [Data Binding Lists](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/ComposeListActivity.kt)
> [tab] Legacy
>
> See the [data binding overview example](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/LegacyDataBindingActivity.kt).
# Fonts
Source: https://rive.app/docs/runtimes/android/fonts
Loading and replacing fonts dynamically at runtime.
## Swapping font assets at runtime
Fonts can be loaded dynamically at runtime. This allows you to localize your Rive content without increasing the file size of the exported .riv file.
Swapping a font asset replaces all instances of the font.
For more information, see [Loading Assets](/docs/runtimes/android/loading-assets).
## Fallback fonts
When rendering text, not all glyphs (characters) may be available in the active font. This commonly occurs when:
* Using custom fonts that don’t support all languages or Unicode ranges
* The embedded font is a subset of the font
* User-generated or dynamic text contains unexpected characters
A fallback font is used automatically when the primary font cannot render a specific glyph. These are typically system fonts, which generally provide broad Unicode coverage.
> [!NOTE]
>
> On Android, font sizes specified for fallback fonts are ignored. Instead, the platform selects system fonts that best match the styling and animation of the text run at runtime.
As of v9.12.0, various options for fallback fonts can be used on Android.
> [!NOTE]
>
> If no fallback fonts are registered, a default system font ("sans-serif") with a regular weight (400, NORMAL) and normal style will be used.
The `Fonts` class provides ways to handle and customize fonts, including retrieving system fonts, defining font options, and finding fallback fonts based on specific characteristics.
### 1. Setting a fallback font
With v9.12.0, the runtime provides a new API to match missing fonts against a specific weight by extending the `FontFallbackStrategy` interface.
This interface contains a single method:
```kotlin theme={null}
fun getFont(weight: Fonts.Weight): List
```
Implementers need to override this method. The user's implementation must then be set as the current fallback strategy via `FontFallbackStrategy.stylePicker`.
> [!WARNING]
>
> `FontFallbackStrategy.stylePicker` is held through a `WeakReference`. Keep a strong reference to your strategy, for example by implementing it on your `Application`. An anonymous object assigned directly to `stylePicker` can be garbage collected.
**Example:**
```kotlin theme={null}
class FontFallback : AppCompatActivity(), FontFallbackStrategy {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Set the fallback strategy
FontFallbackStrategy.stylePicker = this
}
override fun getFont(weight: Fonts.Weight): List {
val desiredWeight = weight.weight
val fonts = listOf(
Fonts.FontOpts(
familyName = "sans-serif",
weight = Fonts.Weight(weight = desiredWeight) // Find a matching weight font
),
// Non-Latin Unicode fallback
Fonts.FontOpts("NotoSansThai-Regular.ttf")
)
return fonts.mapNotNull {
// Filter out fonts that cannot be found on the system
FontHelper.getFallbackFontBytes(it)
}
}
}
```
The method returns a list of `FontBytes` (\`ByteArray\`). The runtime attempts to match the character using the fonts in the list in a first-in, first-out (FIFO) order.
Fallback fonts can also be set using `Rive.setFallbackFont()`, with optional font preferences defined in `Fonts.FontOpts`. These fonts are tried only after attempting the ones returned by `FontFallbackStrategy.getFont()`.
### 2. Font.FontOpts - font options
Defines the font characteristics when selecting a fallback font.
* **Parameters**
* `familyName`: Name of the font family (e.g., "Roboto", "NotoSansThai-Regular.ttf"). Defaults to `null`
* `lang`: Optional language specification. Defaults to `null`
* `weight`: Font weight using `Fonts.Weight` (e.g., `Fonts.Weight.NORMAL`, `Fonts.Weight.BOLD`). Default is `Weight.NORMAL`
* `style`: Font style, either `Fonts.Font.STYLE_NORMAL` or `Fonts.Font.STYLE_ITALIC`. Default is `STYLE_NORMAL`
* **Default example**
```kotlin theme={null}
val defaultFontOpts = Fonts.FontOpts.DEFAULT
```
### 3. Retrieving a fallback font
Use `FontHelper.getFallbackFont()` to find a suitable fallback font based on specified options. Returns a `Fonts.Font` object or `null` if no match is found.
**Example:**
```kotlin theme={null}
val fontOpts = Fonts.FontOpts(familyName = "Roboto", weight = Fonts.Weight.BOLD)
val fallbackFont = FontHelper.getFallbackFont(fontOpts)
```
### 4. Getting font file and bytes
* `FontHelper.getFontFile(font: Fonts.Font)`: Retrieves the file for the specified font.
* `FontHelper.getFontBytes(font: Fonts.Font)`: Reads the font file and returns its bytes.
**Example:**
```kotlin theme={null}
val fontFile = FontHelper.getFontFile(fallbackFont)
val fontBytes = FontHelper.getFontBytes(fallbackFont)
```
### 5. Fonts.Weight - font weight
Represents the font weight, allowing values from 0 to 1000.
* **Predefined Weights**
* `Fonts.Weight.NORMAL` (400)
* `Fonts.Weight.BOLD` (700)
**Example:**
```kotlin theme={null}
val normalWeight = Fonts.Weight.NORMAL
val customWeight = Fonts.Weight.fromInt(500)
```
### 6. Fonts.Style - font style
Represents the font style, allowing "normal" and "italic"
* **Predefined Styles**
* `Fonts.Font.STYLE_NORMAL`
* `Fonts.Font.STYLE_ITALIC`
**Example:**
```kotlin theme={null}
val normalStyle = Fonts.Font.STYLE_NORMAL
val italicStyle = Fonts.Font.STYLE_ITALIC
```
### 7. Getting system fonts
* `FontHelper.getSystemFonts()`: Returns a map of all available system font families.
**Example:**
```kotlin theme={null}
val systemFonts = FontHelper.getSystemFonts()
```
# GPU Canvas
Source: https://rive.app/docs/runtimes/android/gpu-canvas
Enable GPU Canvas in the Android runtime to render 3D and shader content.
GPU Canvas (*deferred rendering* in API names) enables the Rive Android runtime to render 3D and shader content from Rive files. It is available in the Compose API and in the experimental `RiveCanvasSession`, and is enabled when you create a Rive worker. The setting applies to every file loaded with that worker and can't be changed during the worker's lifetime. The legacy `RiveAnimationView` API doesn't support GPU Canvas.
> [!WARNING]
>
> GPU Canvas is experimental. Enabling it requires opting into `ExperimentalDeferredRendering`, and the APIs that enable it may change in future releases.
## Enabling GPU Canvas in Compose
Create the worker with `rememberDeferredRiveWorker`:
```kotlin highlight={1,4} theme={null}
@OptIn(ExperimentalDeferredRendering::class)
@Composable
fun MyRiveScreen() {
val riveWorker = rememberDeferredRiveWorker()
val riveFile = rememberRiveFile(
RiveFileSource.RawRes.from(R.raw.my_rive_file),
riveWorker
)
when (riveFile) {
is Result.Loading -> LoadingIndicator()
is Result.Error -> ErrorMessage(riveFile.throwable)
is Result.Success -> Rive(riveFile.value)
}
}
```
`rememberDeferredRiveWorker` throws a `RiveInitializationException` if the worker can't be created. Its `precompileShaders` option doesn't precompile GPU Canvas shaders.
## Creating the worker yourself
To create a worker outside of composition, pass `enableGPUCanvas = true` to the `RiveWorker` constructor:
```kotlin theme={null}
@OptIn(ExperimentalDeferredRendering::class)
val riveWorker = RiveWorker(enableGPUCanvas = true)
```
This is also how you create a worker for `RiveCanvasSession`, which requires Android 10 (API level 29) or later and opting into `ExperimentalHardwareBitmapRendering`.
You need to release a worker you create. To release it when an activity or fragment is destroyed, call `withLifecycle` in `onCreate`:
```kotlin theme={null}
riveWorker.withLifecycle(this, "MainActivity")
```
Before v11.16.3, you also need to call `beginPolling` on a worker you create yourself. Without it, the worker doesn't deliver results or errors.
## Render backends
GPU Canvas works with both the OpenGL and Vulkan render backends. OpenGL is the default. To use Vulkan, pass `renderBackend` when you create the worker:
```kotlin theme={null}
setContent {
@OptIn(ExperimentalDeferredRendering::class)
val riveWorker = rememberDeferredRiveWorker(renderBackend = RenderBackend.Vulkan)
}
```
The `RiveWorker` constructor takes the same parameter. On devices that can't run Vulkan, the worker can fall back to OpenGL.
Scripts can draw into Rive's render target with `context:gpuTarget()`, but that content only appears with Vulkan. To render on every device, draw into a [GPU canvas](/docs/scripting/api-reference/gpu/gpu-canvas) instead.
## Default behavior
GPU Canvas is disabled by default. You can keep using `rememberRiveWorker` when your content doesn't require it.
See the [GPU Canvas example](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/DeferredRendererActivity.kt) in the Android sample app for a complete setup.
# Handling a lost render context
Source: https://rive.app/docs/runtimes/android/handling-render-context-loss
Detect when a Rive worker loses its GPU device or context, and recover with a new worker.
A render context is the GPU device (Vulkan) or GPU context (OpenGL) that a Rive worker renders with. It can be lost when the GPU driver resets or fails. After that, the worker's Rive instances stop updating. The worker doesn't recover on its own, so your app needs to replace it.
## Detecting a lost render context
As of v11.16.0, you can detect a lost render context with `RiveWorker.renderContextStatus`. This `StateFlow` starts as `RenderContextStatus.Ready` and changes to `RenderContextStatus.Lost` when Rive detects a loss. It never changes back.
Rive detects a loss the next time the worker draws, and updates the status on the main thread. As of v11.16.3, the worker delivers this update automatically. In v11.16.0 to v11.16.2, the status updates while the worker is polled. `rememberRiveWorker` and `rememberRiveWorkerOrNull` poll the worker for you by default while the lifecycle is resumed. If you create a `RiveWorker` yourself on those versions, call `beginPolling`.
`Ready` only means that Rive hasn't detected a loss. It doesn't mean every operation on the worker will succeed, so keep handling the errors that Rive APIs can throw. Rive can also miss some losses, such as one that first shows up while the surface it draws to is being created or resized.
## Recovering with a new worker
To recover, create a new worker and load your content on it again. If you create workers with the `RiveWorker` constructor, release the lost worker yourself. Also close anything you loaded from it without a `remember` function, such as files and images. The old worker shuts down only after it's released and everything loaded from it is closed.
### Recovering in Compose
See the [Compose render context recovery example](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/ComposeRenderContextRecoveryActivity.kt), where an Android `ViewModel` owns the worker.
You can put the worker and everything you load from it inside a `key` block, and change the key when the status changes to `Lost`. When the key changes, Compose disposes the block. The `remember` functions in it close what they loaded and release the old worker. The block then runs again with a new worker.
Creating the new worker can fail, so the example below uses `rememberRiveWorkerOrNull`. It returns `null` instead of throwing, which lets you show a fallback.
```kotlin highlight={2,3,10-14} theme={null}
setContent {
var workerGeneration by remember { mutableIntStateOf(0) }
key(workerGeneration) {
val errorState = remember { mutableStateOf(null) }
val riveWorker = rememberRiveWorkerOrNull(errorState)
if (riveWorker == null) {
// Show a fallback. Changing workerGeneration tries again.
ErrorMessage(errorState.value)
} else {
LaunchedEffect(riveWorker) {
// Waits until the worker loses its render context.
riveWorker.renderContextStatus.first { it == RenderContextStatus.Lost }
workerGeneration++
}
val riveFile = rememberRiveFile(
RiveFileSource.RawRes.from(R.raw.my_rive_file),
riveWorker
)
when (riveFile) {
is Result.Loading -> LoadingIndicator()
is Result.Error -> /* Handle the error */
is Result.Success -> Rive(riveFile.value)
}
}
}
}
```
### Recovering with `RiveCanvasSession`
The experimental `RiveCanvasSession` stops advancing and rendering after a loss, but `beginPlaying` doesn't return until you close the session or cancel its coroutine. Watch `renderContextStatus` yourself, then close the session and what you loaded, and create them again on a new worker. See the [Canvas render context recovery example](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/CanvasRenderContextRecoveryActivity.kt).
### Loading assets again
Assets embedded in the Rive file load again with the file. Images, fonts, and audio that you load yourself can only be used on the worker that loaded them, so load them again on the new worker. Keep their bytes, or be ready to download them again.
### Restoring state
Everything on the new worker starts from its initial state. State machines start from their entry state, and new view model instances have their initial values. If your app changed view model properties, set them again on the new view model instance. Setting them again changes a state machine's state only if its transitions use those properties.
# Layout
Source: https://rive.app/docs/runtimes/android/layouts
Control how graphics are laid out within the canvas.
## The Fit Mode
A Rive graphic authored in the editor will not necessarily match the size of the container it is rendered into at runtime. We need to determine the behavior for this scenario, as no one size fits all.
The solution is choosing the fit mode. This is specified on the container and controls how Rive is scaled.
* `Layout`: Use the Rive layout engine to apply responsive layout to the artboard, matching the container dimensions. For this to work, the artboard must be designed with layouts in mind. See [Responsive Layouts](#responsive-layouts) for more information on how to use this option.
* `Contain`: **(Default)** Preserve aspect ratio and scale the artboard so that its larger dimension matches the corresponding dimension of the container.
If aspect ratios are not identical, this will leave space on the shorter dimension's axis.
* `ScaleDown`: Preserve aspect ratio and behave like `Contain` when the artboard is larger than the container. Otherwise, use the artboard's original dimensions.
* `Cover`: Preserve aspect ratio and scale the artboard so that its smaller dimension matches the corresponding dimension of the container.
If aspect ratios are not identical, this will clip the artboard on the larger dimension's axis.
* `FitWidth`: Preserve aspect ratio and scale the artboard width to match the container's width.
If the aspect ratios between the artboard and container do not match, this will result in either vertical clipping or space in the vertical axis.
* `FitHeight`: Preserve aspect ratio and scale the artboard height to match the container's height.
If the aspect ratios between the artboard and container do not match, this will result in either horizontal clipping or space in the horizontal axis.
* `Fill`: Do not preserve aspect ratio and stretch to the container's dimensions.
* `None`: Do not scale. Use the artboard's original dimensions.
For either dimension, if the artboard's dimension is larger, it will be clipped. If it is smaller, it will leave space.
### Alignment
In all options other than `Layout` and `Fill`, there is the possibility that the Rive graphic is clipped or leaves space within its container. Alignment determines how content aligns within the container. The following options are available.
* `TopLeft`
* `TopCenter`
* `TopRight`
* `CenterLeft`
* `Center` **(Default)**
* `CenterRight`
* `BottomLeft`
* `BottomCenter`
* `BottomRight`
### Applying the Fit Mode
> [tab] Compose
>
> The `Fit` sealed class is used to specify the fit mode. On all variants other than `Layout` and `Fill`, the `Alignment` enum can be supplied to specify the alignment. Note that because this is a class, it must be constructed. If an alignment is not provided, it defaults to `Alignment.Center`.
>
> ```kotlin theme={null}
> Rive(
> myRiveFile,
> fit = Fit.Cover(Alignment.TopCenter)
> )
> ```
> [tab] Legacy
>
> The `Fit` enum specifies the fit mode with the following options: `LAYOUT`, `CONTAIN`, `SCALE_DOWN`, `COVER`, `FIT_WIDTH`, `FIT_HEIGHT`, `FILL`, and `NONE`.
>
> The `Alignment` enum specifies the alignment with the following options: `TOP_LEFT`, `TOP_CENTER`, `TOP_RIGHT`, `CENTER_LEFT`, `CENTER`, `CENTER_RIGHT`, `BOTTOM_LEFT`, `BOTTOM_CENTER`, and `BOTTOM_RIGHT`.
>
> ### Using XML Layouts
>
> The fit and alignment enum values can be applied to the `riveFit` and `riveAlignment` attributes in your XML layout:
>
> ```xml theme={null}
> android:layout_width="match_parent"
> android:layout_height="match_parent"
> app:riveResource="@raw/my_rive_file"
> app:riveAlignment="CENTER"
> app:riveFit="CONTAIN"
> />
> ```
>
> ### Using Kotlin
>
> The fit and alignment enum values can be applied to the `fit` and `alignment` properties on your `RiveAnimationView` instance:
>
> ```kotlin theme={null}
> animationView.fit = Fit.FILL
> animationView.alignment = Alignment.CENTER
> ```
## Responsive Layouts
Rive’s layout feature lets you design resizable artboards with built-in responsive behavior, configured from the editor. Ensure the fit mode is set to **Layout** at runtime and the artboard will resize to fill its container according to the constraints defined in the editor.
Optionally you may provide a **layout scale factor** to multiply the scale of the content. This allows fine tuning the visual size within your container. This property only applies when setting the **Fit** mode to **Layout**.
For more Editor information and how to configure your graphic, see [Layouts Overview](/docs/editor/layouts/layouts-overview).
> [tab] Compose
>
> See also the [Compose Layout](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/ComposeLayoutActivity.kt) sample.
>
> Set the `fit` parameter to `Fit.Layout` in the `Rive` composable. This will resize the artboard to match the container size. The `Fit.Layout` constructor takes an optional `layoutScaleFactor` parameter to adjust the scale of the artboard. By default it is 1, i.e. no scaling.
>
> ```kotlin theme={null}
> Rive(
> myRiveFile,
> fit = Fit.Layout(1.2f) // 1.2x scale
> )
> ```
> [tab] Legacy
>
> ### Sample
>
> See the [Layout](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/LayoutActivity.kt) sample.
>
> ### Using XML Layouts
>
> Set the `riveFit` attribute to `"LAYOUT"`.
>
> ```kotlin theme={null}
> ...
> app:riveFit="LAYOUT"
> />
> ```
>
> ### Using Kotlin
>
> Set the RiveAnimationView's `fit` property to `LAYOUT`.
>
> ```kotlin theme={null}
> val animationView = findViewById(R.id.my_view)
> animationView.fit = Fit.LAYOUT
> ```
>
> ### Adjusting the Layout Scale Factor
>
> To adjust the scale factor of the contents, use the `layoutScaleFactor` property. This is nullable, so by default, it will use the density as reported by `resources.displayMetrics.density`. You can override this to any positive float value, or return control to the system by resetting to `null`:
>
> ```kotlin theme={null}
> // Force a set scale factor
> animationView.layoutScaleFactor = 2.5f
> // Reset to system control
> animationView.layoutScaleFactor = null
> ```
>
> ### Resizing the Artboard
>
> The artboard size can be manually controlled by using the `width` and `height` properties. `resetArtboardSize()` can be used to return these values to their defaults.
>
> ```kotlin theme={null}
> // Force a certain artboard size
> animationView.controller.activeArtboard?.width = 1000f
> animationView.controller.activeArtboard?.height = 1000f
> // Reset the artboard size to defaults
> animationView.controller.activeArtboard?.resetArtboardSize()
> ```
# Getting Started (Legacy API)
Source: https://rive.app/docs/runtimes/android/legacy-getting-started
Getting started instructions for the Rive Android Legacy API.
## Adding Rive to your project
See the [Adding Rive to Your Project](/docs/runtimes/android/android#adding-rive-to-your-project) section for instructions on adding Rive to your Android project. Once complete, resume here.
## Building a RiveAnimationView
There are a number of ways to add Rive animations to your Android application.
Before getting started, ensure your Rive files (.riv) are included in your Android project. The recommended way is to add them to the raw resources (`res/raw`) folder of your project.
### Using setRiveResource or setRiveUrl
For the simplest programmatic initialization, use `setRiveResource` (local) or `setRiveUrl` (networked) methods. They have a number of optional parameters to customize the view.
```kotlin theme={null}
class MyActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val riveView = RiveAnimationView(this)
riveView.setRiveResource(R.raw.my_rive_file)
// or
riveView.setRiveUrl("https://mycdn.myorg.com/my_rive_file.riv")
setContentView(riveView)
}
}
```
### Using RiveAnimationView.Builder
Rive also provides a builder pattern for constructing a `RiveAnimationView` which allows for staggered initialization steps. Note that the `setResource` method can take a raw resource ID, a URL (string), a byte array, or a Rive `File`.
```kotlin theme={null}
val riveView = RiveAnimationView.Builder(this)
.setResource(R.raw.my_rive_file)
// or
.setResource("https://mycdn.myorg.com/my_rive_file.riv")
.build()
setContentView(riveView)
```
### Using a Rive file
If you have already loaded a Rive `File` instance, you can use that to initialize the view as well. See [Caching a Rive File](/docs/runtimes/caching-a-rive-file) for more details on how and why to load Rive files.
```kotlin theme={null}
// Loads bytes on the main thread for simplicity; consider loading on a background thread for production use.
val bytes = resources.openRawResource(R.raw.rating).use { res -> res.readBytes() }
val riveFile = File(bytes)
val riveView = RiveAnimationView(this)
riveView.setRiveFile(riveFile)
// Release the file if you no longer need it, keep if you plan to reuse it.
riveFile.release()
setContentView(riveView)
```
### Using Compose (AndroidView)
You can also use `RiveAnimationView` inside a Compose UI using the `AndroidView` composable. See also the [LegacyComposeActivity](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/LegacyComposeActivity.kt) in the example app.
```kotlin theme={null}
setContent {
AndroidView(
factory = { context ->
RiveAnimationView(context).also {
it.setRiveResource(R.raw.my_rive_file)
}
}
)
}
```
### Using XML Layouts
To use XML, include it as part of your layout. It has a number of optional attributes to customize the view.
```xml theme={null}
```
If you would rather load the Rive file from a hosted location, use the `app:riveUrl` attribute. Ensure you have the necessary [internet permissions](#internet-permissions).
```xml theme={null}
```
From your activity you can load it as usual:
```kotlin theme={null}
setContentView(R.layout.my_layout)
```
## Internet permissions
If you're retrieving Rive files over a network, your app will need permission to access the internet in `AndroidManifest.xml`:
```xml theme={null}
```
Note that this isn't necessary if you include the .riv files in your Android project and load them as raw resources.
See the pages in the "Runtime Fundamentals" section to learn how to control animation playback, state machines, and more.
# Loading Assets
Source: https://rive.app/docs/runtimes/android/loading-assets
Loading and replacing assets dynamically at runtime
> [!NOTE]
>
> If you want to dynamically replace images, use [image data binding](data-binding#images).
Some Rive files may contain assets that can be embedded within the actual file binary, such as font, image, or audio files. The Rive runtimes may then load these assets when the Rive file is loaded. While this makes for easy usage of the Rive files/runtimes, there may be opportunities to load these assets in or even replace them at runtime instead of embedding them in the file binary.
There are several benefits to this approach:
* Keep the `.riv` files tiny without potential bloat of larger assets
* Dynamically load an asset for any reason, such as loading an image with a smaller resolution if the `.riv` is running on a mobile device vs. an image of a larger resolution for desktop devices
* Preload assets to have available immediately when displaying your `.riv`
* Use assets already bundled with your application, such as font files
* Sharing the same asset between multiple `.riv`s
## Methods for loading assets
There are currently three different ways to load assets for your Rive files.
In the Rive editor select the desired asset from the **Assets** tab, and in the inspector choose the desired export option:

### Embedded assets
In the Rive editor, static assets can be included in the `.riv` file, by choosing the *"Embedded"* export type. As stated in the beginning of this page, when the Rive file gets loaded, the runtime will implicitly attempt to load in the assets embedded in the `.riv` as well, and you don't need to concern yourself with loading any assets manually.
**Caveat:** Embedded assets may bulk up the file size, especially when it comes to fonts when using Rive Text ([Text Overview](/docs/editor/text/text-overview)).
> [!NOTE]
>
> **Embedded is the default option.**
### Loading via Rive's CDN
In the Rive editor, you can mark an imported asset as a *"Hosted"* export type, which means that when you export the `.riv` file, the asset will not be embedded in the file binary, but will be hosted on Rive's CDN. This means that at runtime when loading in the file, the runtime will see the asset is marked as "Hosted" and load the asset in from the Rive CDN, so that you don't need to concern yourself with loading anything yourself, and the file can still remain tiny.
**Caveat:** The app will make an extra call to a Rive CDN to retrieve your asset
> [!NOTE]
>
> Hosted assets are available on Voyager and Enterprise plans. [Learn more about
> our plans and pricing](https://rive.app/pricing?utm_source=docs\&utm_medium=content).
### Image CDNs
Some image CDNs allow for on-the-fly image transformations, including resizing, cropping, and automatic format conversion based on the browser's and device's capabilities. These CDNs can host your Rive image assets. Note that for these CDNs, you may need to specify the accepted formats, for example, as part of the HTTP header request:
```html theme={null}
... headers: { Accept: 'image/png,image/webp,image/jpeg,*/*', } ...
```
Please see your CDN provider's documentation for additional information.
> [!WARNING]
>
> Rive supports the following image formats: **jpeg**, **png**, and **webp**
### Referenced assets
In the Rive editor, you can mark an imported asset as a *"Referenced"* export type, which means that when you export the `.riv` file, the asset will not be embedded in the file binary, and the responsibility of loading the asset will be handled by your application at runtime.
This option enables you to dynamically load in assets via a handler API when the runtime begins loading in the `.riv` file. This option is preferable if you have a need to dynamically load in a specific asset based on any kind of app/game logic, and especially if you want to keep the .riv file size small.
All referenced assets, including the `.riv`, will be bundled as a zip file when you export your animation.
**Caveat:** You will need to provide an asset handler API when loading in Rive which should do the work of loading in an asset yourself. See [Handling Assets](#handling-assets).
> [!NOTE]
>
> SVG assets can't currently be loaded at runtime as referenced assets.
>
> This is because SVGs are converted to Rive vector objects, which are always embedded into the .riv.
## Handling assets
### Examples
* [https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/AssetLoaderFragment.kt](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/AssetLoaderFragment.kt)
### Using the Asset Handler API
When instantiating a new `RiveAnimationView`, set a new attribute called `riveAssetLoaderClass` whose value is a string name of the full path to a class that will be responsible for either handling the load of an asset at runtime or passing on the responsibility and giving the runtime a chance to load it otherwise.
**via XML**
```kotlin theme={null}
```
In your accompanying activity, create a new class with the name provided to `riveAssetLoaderClass`, who should implement the `ContextAssetLoader` abstract class from the Rive runtime. Here, you can override a `loadContents` function, which will do the work of determining what assets (if any) to load:
* `asset` - Reference to a `FileAsset` object. You can grab a number of properties from this object, such as the name, asset type, and more. You'll also use this to set a new Rive-specific asset for the dynamically loaded in asset you want to set
* `bytes` - Array of bytes for the asset (if possible, such as if it's an embedded asset)
```kotlin theme={null}
override fun loadContents(asset: FileAsset, inBandBytes: ByteArray): Boolean
```
**Important**: Note that the return value is a `boolean`, which is where you need to return `true` if you intend on handling and loading in an asset yourself, or `false` if you do not want to handle asset loading for that given asset yourself, and attempt to have the runtime try to load the asset.
**Example Usage**
To accompany the XML snippet above, here's an example of what the accompanying activity may look like:
```kotlin theme={null}
package app.rive.runtime.example
import android.content.Context
import android.os.Bundle
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import app.rive.runtime.kotlin.core.ExperimentalAssetLoader
import app.rive.runtime.kotlin.core.FileAsset
import app.rive.runtime.kotlin.core.ContextAssetLoader
import kotlin.random.Random
class FontLoadActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.rive_font_load_simple)
}
}
open class HandleSimpleRiveAsset(context: Context) : ContextAssetLoader(context) {
private val fontPool = arrayOf(
R.raw.montserrat,
R.raw.opensans,
)
/**
* Override this method to customize the asset loading process.
*/
override fun loadContents(asset: FileAsset, inBandBytes: ByteArray): Boolean {
val randFontIndex = Random.nextInt(fontPool.size)
val fontToLoad = fontPool[randFontIndex]
context.resources.openRawResource(fontToLoad).use {
// Load in the font bytes to the asset
return asset.decode(it.readBytes())
}
}
}
```
## Additional resources
[YouTube video player](https://www.youtube.com/embed/BrWBmZwouQQ)
# Logging
Source: https://rive.app/docs/runtimes/android/logging
This Rive runtime includes logging capabilities to help with debugging. These logs are *only* for debugging purposes; nothing is sent over the network, and no personally identifiable information (PII) is logged.
The table below showcases the runtimes that support logging.
> [tab] Compose
>
> The new runtime includes a fine-grained, flexible logging system that allows you to capture logs at various levels (debug, info, warning, error) and redirect them to your preferred logging framework or sink. This is done by implementing the `RiveLog.Logger` interface and assigning the global `RiveLog.logger` property.
>
> The library ships with a default implementation that logs to Android Logcat. Enable it with the following:
>
> ```kotlin theme={null}
> RiveLog.logger = RiveLog.LogcatLogger()
> ```
> [tab] Legacy
>
> Fine-grained Logging is not supported in the legacy runtime. We may consider retrofitting more logging capabilities to the legacy runtime in the future, especially if doing so would illuminate a potential source for bugs.
# Migrating from the Legacy Rive Android Runtime
Source: https://rive.app/docs/runtimes/android/migrating-from-legacy
A guide to help you transition from the legacy Rive Android runtime to the new runtime.
## Overview
The [new Rive Android runtime](/docs/runtimes/android/android) is a **near-complete rewrite** of both the public API and the internal architecture. While conceptually most operations have an equivalent, the two APIs are incompatible. Any existing work in the legacy API that you would like to migrate must be rebuilt using the new API. This guide aims to demonstrate how to migrate each feature area.
This guide covers:
1. [Shared Features](#shared-features) - Common operations and their equivalents.
2. [New Exclusive Features](#new-exclusive-features) - Features available only in the new runtime.
3. [Legacy Exclusive Features](#legacy-exclusive-features) - Features no longer supported in the new runtime. Most have workarounds or alternatives; these removals simplify the API surface, reduce maintenance overhead, and eliminate anti-patterns.
> [!NOTE]
>
> This guide is not meant to be exhaustive as it would be redundant with existing general documentation. Please refer to the relevant sections of the documentation for more details on specific topics.
## Package
The legacy Rive Android runtime is provided in the `app.rive.runtime.kotlin` package (+ `.core`). The new runtime is provided in the `app.rive` package (+ `.core`). This allows identical class names, such as `Artboard` to coexist without conflict. If you need to use identically named classes from both packages in the same file, you can use Kotlin's `import as` feature to alias one of the imports.
```kotlin theme={null}
import app.rive.Artboard
import app.rive.runtime.kotlin.core.Artboard as LegacyArtboard
```
## Asynchronous APIs
Due to the new threading model based on the `RiveWorker`, almost all operations which return values that were originally synchronous on the main thread are now asynchronous `suspend` functions, e.g. loading Rive files and performing queries. You will need to call these functions from a coroutine context, such as within a `LaunchedEffect` in Compose or using `lifecycleScope.launch` in an Activity or Fragment.
The most common Compose operations are wrapped in helpers, such as `rememberRiveFile`, which expose the async state as a `Result` type for easier consumption in Composables. Other operations are "fire and forget", such as creating artboards and view model instances from a loaded Rive file, or advancing a state machine.
## Lifecycles
The legacy Rive Android runtime is View based, with the `RiveAnimationView` class managing its lifecycle based on the owning Activity or Fragment lifecycle. The Rive file's lifetime is associated with the view's, as well as the renderer, controller, and created objects such as artboards and state machines. These used hierarchical reference counting to manage their lifetimes.
The new runtime makes use of the `AutoCloseable` interface to manage lifetimes explicitly for objects such as the Rive file, artboards, and state machines. The worker by contrast is reference counted and owns all memory for resources it creates. When creating objects manually, you must `close` them to free their resources or they will last for the duration of the worker. Alternatively, you can use them with the `use` helper, which will call `close` at the end of its block. The worker itself must have all references released or it and its resources will leak.
In Compose, lifecycles are tied to `remember` Composables and use `DisposableEffect` to create and dispose of objects as needed, simplifying memory management.
## Shared features
### Shared APIs
A few APIs are shared between the legacy and new runtimes. They are still in the `app.rive.runtime.kotlin` package of the legacy runtime.
* The `Rive` global object for initialization, including the `Rive.init` method.
* The `RiveInitializer` XML initialization helper.
* The fallback font APIs, including the `FontFallbackStrategy` interface and the `FontFallbackStrategy.stylePicker` global.
These shared APIs may change in the future to be fully separated with revised versions in the new package. This will only happen as a breaking change in a major version release.
### RiveAnimationView to Rive
The legacy Rive Android runtime is View based and provided the `RiveAnimationView` class to display Rive animations. The name reflects the more limited feature set at the time of its creation, being mostly for animation playback.
The new API is Compose based, with the intention to provide a View API in the future. The main Composable is simply called `Rive`, reflecting the broader feature set and use cases it supports.
#### Setting a local raw resource
> [!NOTE]
>
> The new API will use the I/O dispatcher by default to load Rive files asynchronously. This is different from the legacy runtime, which loaded files synchronously on the main thread. If you want to load files using a different threading model, load the resource using your preferred method and pass the bytes to a `RiveFileSource.Bytes` source.
**Legacy RiveAnimationView**
```kotlin theme={null}
// Builder API
val riveView = RiveAnimationView.Builder(context)
.setResource(R.raw.my_rive_file)
.build()
// Set method
val riveView = RiveAnimationView(context)
riveView.setRiveResource(R.raw.my_rive_file)
```
**Legacy XML Layout**
```xml theme={null}
```
**New Rive Composable**
```kotlin theme={null}
val riveWorker = rememberRiveWorker()
val riveFile = rememberRiveFile(
RiveFileSource.RawRes.from(R.raw.my_rive_file),
riveWorker
)
when (riveFile) {
is Result.Success -> Rive(riveFile.value)
else -> {} // Handle loading and error states appropriately
}
```
#### Setting a Rive file from bytes
**Legacy RiveAnimationView**
```kotlin theme={null}
// Builder API
val riveView = RiveAnimationView.Builder(context)
.setResource(myBytes)
.build()
// Set method
val riveView = RiveAnimationView(context)
riveView.setRiveBytes(myBytes)
```
**New Rive Composable**
```kotlin theme={null}
val riveWorker = rememberRiveWorker()
val riveFile = rememberRiveFile(
RiveFileSource.Bytes(myBytes),
riveWorker
)
when (riveFile) {
is Result.Success -> Rive(riveFile.value)
else -> {} // Handle loading and error states appropriately
}
```
#### Caching a Rive file
> [card]
>
> See also Caching a Rive File for more details.
>
> [Open](/docs/runtimes/android/caching-a-rive-file)
In the new runtime, Rive files are always created explicitly, as opposed to often being created implicitly by the view. This makes it more obvious to cache and reuse Rive files across multiple Rive instances.
**Legacy RiveAnimationView**
```kotlin theme={null}
// Load bytes on the main thread for simplicity; consider loading on a background thread for production use.
val bytes = resources.openRawResource(R.raw.my_rive_file).use { res -> res.readBytes() }
val riveFile = File(bytes)
// Builder API
val riveView = RiveAnimationView.Builder(context)
.setResource(riveFile)
.build()
// Set method
val riveView = RiveAnimationView(context)
riveView.setRiveFile(riveFile)
// Release the file if you no longer need it, keep if you plan to reuse it.
riveFile.release()
```
**New Rive Composable**
The Rive file produced by `rememberRiveFile` can be hoisted to a higher level Composable to live longer and be shared across multiple Rive instances.
```kotlin theme={null}
val riveWorker = rememberRiveWorker()
val riveFile = rememberRiveFile(
RiveFileSource.RawRes.from(R.raw.my_rive_file),
riveWorker
)
when (riveFile) {
is Result.Success -> Rive(riveFile.value)
else -> {} // Handle loading and error states appropriately
}
```
#### Choosing an Artboard and State Machine
> [card]
>
> See also the artboard documentation for more details.
>
> [Open](/docs/runtimes/android/artboards)
> [card]
>
> See also the state machine documentation for more details.
>
> [Open](/docs/runtimes/android/state-machines)
**Legacy RiveAnimationView**
```kotlin theme={null}
// Builder API
val riveView = RiveAnimationView.Builder(context)
.setResource(R.raw.my_rive_file)
.setArtboardName("My Artboard")
.setStateMachineName("My State Machine")
.build()
// Set method
val riveView = RiveAnimationView(context)
riveView.setRiveResource(R.raw.my_rive_file,
artboardName = "My Artboard",
stateMachineName = "My State Machine"
)
```
**Legacy XML Layout**
```xml theme={null}
```
**New Rive Composable**
Artboards and state machines are passed as objects rather than names. You can use the `rememberArtboard` and `rememberStateMachine` helpers to get these objects from a loaded `RiveFile`.
```kotlin theme={null}
val riveWorker = rememberRiveWorker()
val riveFile = rememberRiveFile(
RiveFileSource.RawRes.from(R.raw.my_rive_file),
riveWorker
)
when (riveFile) {
is Result.Success -> {
val artboard = rememberArtboard(riveFile.value, "My Artboard")
val stateMachine = rememberStateMachine(artboard, "My State Machine")
Rive(
riveFile.value,
artboard = artboard,
stateMachine = stateMachine
)
}
else -> {} // Handle loading and error states appropriately
}
```
#### Setting the Fit and Alignment
> [card]
>
> See also the Layout documentation for more details.
>
> [Open](/docs/runtimes/android/layouts)
**Legacy RiveAnimationView**
```kotlin theme={null}
// Builder API
val riveView = RiveAnimationView.Builder(context)
.setResource(R.raw.my_rive_file)
.setFit(Fit.CONTAIN)
.setAlignment(Alignment.CENTER)
.build()
// Set method
val riveView = RiveAnimationView(context)
riveView.setRiveResource(R.raw.my_rive_file,
fit = Fit.CONTAIN,
alignment = Alignment.CENTER
)
// Property
riveView.controller.fit = Fit.CONTAIN
riveView.controller.alignment = Alignment.CENTER
```
**Legacy XML Layout**
```xml theme={null}
```
**New Rive Composable**
The new runtime models fit modes as a sealed class, allowing alignment only on variants that support it. Additionally, the `Layout` variant exposes the layout scale factor.
```kotlin theme={null}
Rive(
riveFile,
fit = Fit.Contain(Alignment.Center),
)
```
#### Auto Binding
> [card]
>
> See also the auto binding section in data binding for more details.
>
> [Open](/docs/runtimes/android/data-binding)
**Legacy RiveAnimationView**
```kotlin theme={null}
// Builder API
val riveView = RiveAnimationView.Builder(context)
.setResource(R.raw.my_rive_file)
.setAutoBind(true)
.build()
// Set method
val riveView = RiveAnimationView(context)
riveView.setRiveResource(R.raw.my_rive_file, autoBind = true)
```
**Legacy XML Layout**
```xml theme={null}
```
**New Rive Composable**
Auto-binding was not implemented in the Compose API due to the nature of composables. Since they are functions, it is difficult to get values out of them as compared to classes. Callbacks would require a null placeholder to remember the value before it has fired which creates more overhead than supplying the instance directly.
The equivalent is to create a view model instance with no source. This will internally create the default artboard, the default view model for that artboard, and the default instance for that view model. You can then pass that into the Rive composable.
```kotlin theme={null}
val vmi = rememberViewModelInstance(riveFile)
Rive(
riveFile,
viewModelInstance = vmi,
)
```
#### Playing, pausing, and State Machine settling
**Legacy RiveAnimationView**
The legacy API includes `play()` and `pause()` methods on the `RiveAnimationView` class to control playback of the animation. Notably, the paused state is the same as the settled state, which is not ideal. `play()` will both unpause and unsettle the state machine, causing it to advance.
```kotlin theme={null}
riveView.play() // Unsettles and plays
riveView.pause() // Pauses
```
**New Rive Composable**
In the new runtime, there are no play or pause methods. Instead, control of the play state is done through the `playing` parameter on the `Rive` Composable. Setting `playing` to `false` will pause the animation, while setting it to `true` will resume it. State machine settling and unsettling is done automatically and covers all scenarios that would require it.
```kotlin theme={null}
var isPlaying by remember { mutableStateOf(true) }
Rive(
riveFile,
playing = isPlaying
)
```
#### Autoplay and setting initial values
The legacy runtime includes an `autoplay` feature, defaulting to true, that automatically starts playing the given animation or state machine when the Rive file is loaded. This can be disabled to allow setting initial values before playback begins.
**Legacy RiveAnimationView**
```kotlin theme={null}
// Builder API
val riveView = RiveAnimationView.Builder(context)
.setResource(R.raw.my_rive_file)
.setAutoPlay(true)
.build()
// Set method
val riveView = RiveAnimationView(context)
riveView.setRiveResource(R.raw.my_rive_file, autoPlay = true)
```
**Legacy XML Layout**
```xml theme={null}
```
The new runtime does not include an `autoplay` feature as it is not necessary due to the decoupling of Rive files from their presentation. You can leave `playing` at its default value of `true` to achieve similar behavior. To set initial values before playback begins, you can set `playing` to `false`, update your data-bound properties, and then set `playing` to `true` to start playback.
```kotlin theme={null}
var isPlaying by remember { mutableStateOf(false) }
val vmi = rememberViewModelInstance(riveFile)
LaunchedEffect(vmi) {
// Set initial values
vmi.setNumber("My Number Property", 42.0f)
// Start playback
isPlaying = true
}
Rive(
riveFile,
playing = isPlaying,
viewModelInstance = vmi,
)
```
#### Touch pass-through
**Legacy RiveAnimationView**
```kotlin theme={null}
// Builder API
val riveView = RiveAnimationView.Builder(context)
.setResource(R.raw.my_rive_file)
.setTouchPassThrough(true)
.build()
// Property
riveView.touchPassThrough = true
```
**Legacy XML Layout**
```xml theme={null}
```
**New Rive Composable**
The new runtime provides the `touchPassThrough` parameter on the `Rive` Composable. This is more nuanced, as it can be set to `Consume` (default behavior), `Observe`, or `PassThrough`. `Observe` shares only with ancestors in the Compose hierarchy, useful for not blocking scroll events, while `PassThrough` also shares with siblings (equivalent to the legacy behavior).
```kotlin theme={null}
Rive(
riveFile,
touchPassThrough = RivePointerInputMode.PassThrough,
)
```
### View Models
**Legacy**
The legacy runtime includes a `ViewModel` class retrieved from a `File` which corresponds to a view model in the Rive Editor. This class provides methods to query and create view model instances.
```kotlin theme={null}
val viewModel = riveFile.getViewModelByName("My View Model")
val instance = viewModel.createInstanceFromName("My Instance")
val properties = viewModel.properties
```
**New**
The new runtime collapses querying into the `RiveFile` class, where the view model name is included when required for queries. View model instances are specified by a `ViewModelSource`, which can be either `Named` or `DefaultForArtboard`. This `ViewModelSource` can then be converted into a `ViewModelInstanceSource` using the `blankInstance`, `defaultInstance`, or `namedInstance` helpers. This completed source can then be passed to `rememberViewModelInstance` or `ViewModelInstance.fromFile`.
```kotlin theme={null}
val instanceSource = ViewModelSource.Named("My View Model").namedInstance("My Instance")
val instance = rememberViewModelInstance(riveFile, instanceSource)
LaunchedEffect(riveFile) {
val properties = riveFile.getViewModelProperties("My View Model")
}
```
### View Model instance properties
**Legacy**
The legacy runtime provides explicit property objects on the `ViewModelInstance` class for querying and updating data-bound properties.
```kotlin theme={null}
// Getting a property
val numberProperty = vmi.getNumberProperty("My Number Property")
// Reading its value
val numberValue = numberProperty.value
// Observing its value
numberProperty.valueFlow.collect { value ->
// Handle value updates
}
// Writing its value
numberProperty.value = 42.0f
```
**New**
The new runtime does not provide explicit property objects. Instead, properties are queried and updated on the `ViewModelInstance` by name using getter and setter methods.
```kotlin theme={null}
LaunchedEffect(vmi) {
// Reading a property value
val numberValue = vmi.getNumberFlow("My Number Property").first()
// Observing its value
vmi.getNumberFlow("My Number Property").collect { value ->
// Handle value updates
}
}
// Observing in Compose
val numberValue by vmi.collectNumberAsState("My Number Property", initial = 0.0f)
// Writing a property value
vmi.setNumber("My Number Property", 42.0f)
```
### Bindable Artboards
**Legacy**
The legacy runtime includes a `BindableArtboard` class that wraps a native `Artboard` and provides data-binding capabilities. This class is meant to limit the API surface and prevent anti-patterns by restricting direct access to the underlying artboard.
```kotlin theme={null}
val bindableArtboard = riveFile.createBindableArtboardByName("My Artboard")
val artboardProperty = vmi.getArtboardProperty("My Artboard Property")
artboardProperty.set(bindableArtboard)
```
**New**
The new runtime does not include a `BindableArtboard` class. Instead, the same `Artboard` class is used in both cases.
```kotlin theme={null}
val artboard = rememberArtboard(riveFile, "My Artboard")
vmi.setArtboard("My Artboard Property", artboard)
```
### Loading referenced assets
**Legacy**
The legacy runtime uses a "pull" model for loading referenced assets, where the runtime requests assets by callback as needed through the `FileAssetLoader` class or its subclasses. This allows lazy loading of assets, but removes control from the user for when assets are loaded.
**Legacy RiveAnimationView**
```kotlin theme={null}
class MyAssetLoader(private val context: Context) : ContextAssetLoader(context) {
// Example asset loader that handles one image asset named "my_image"
override fun loadContents(asset: FileAsset, inBandBytes: ByteArray): Boolean {
val identifier =
if (asset.uniqueFilename == "my_image") R.raw.my_image
else return false
context.resources.openRawResource(identifier).use {
asset.decode(it.readBytes())
}
return true
}
}
// Builder API
val riveView = RiveAnimationView.Builder(context)
.setResource(R.raw.my_rive_file)
.setAssetLoader(MyAssetLoader(context))
.build()
// Set method
val riveView = RiveAnimationView(context)
riveView.setAssetLoader(MyAssetLoader(context))
riveView.setRiveResource(R.raw.my_rive_file)
```
**Legacy XML Layout**
```xml theme={null}
```
**New**
The new runtime uses a "push" model, where the application is responsible for supplying referenced assets to the worker before they are needed. If assets are supplied after they are required, they will "pop in" instead. This change was made to simplify the internal architecture and to allow users the flexibility to load assets in whatever manner they choose.
The current way to retrieve the list of required assets is through inspecting the files in the exported .zip. In the future we will add an API to query the manifest of required assets from a Rive file.
Assets are "global" to the worker, meaning they can be shared across multiple Rive files and instances, assuming they have the same key. This reduces memory usage for common assets such as fonts.
```kotlin theme={null}
val riveWorker = rememberRiveWorker()
val bytesResult = produceState>(Result.Loading) {
value = withContext(Dispatchers.IO) {
context.resources.openRawResource(R.raw.my_image)
.use { Result.Success(it.readBytes()) }
}
}.value
val image = bytesResult.andThen { bytes -> rememberRegisteredImage(riveWorker, "My Image", bytes) }
```
### Default Layout Scale Factor
The legacy runtime uses the reported device density as the default scale factor when rendering Rive with Layout as the fit mode.
The new runtime uses a default scale factor of 1.0, meaning Rive units map directly to screen pixels. In practice, matching density often results in visuals appearing too large. However, if that is the desired behavior and you want to match the legacy runtime, you can set the scale factor to the device density using `LocalDensity`.
```kotlin theme={null}
val density = LocalDensity.current.density
Rive(
riveFile,
fit = Fit.Layout(scaleFactor = density)
)
```
## New exclusive features
A growing number of features are only available in the new runtime. These features were added to address limitations in the legacy runtime or to provide new capabilities that were not previously possible. Below is a list of such features along with brief descriptions.
### Logging
The new runtime includes a fine-grained, flexible [Logging](/docs/runtimes/android/logging) system that allows you to capture logs at various levels (debug, info, warning, error) and redirect them to your preferred logging framework or sink.
By comparison, the legacy runtime has limited logs.
We may consider retrofitting more logging capabilities to the legacy runtime in the future, especially if doing so would illuminate a potential source for bugs.
### Tracking the loading state of a Rive file
The new runtime provides a `Result` wrapper around Rive file loading operations, allowing you to track the state (loading, success, error) of a Rive file. This is useful for providing user feedback during loading or handling errors gracefully.
```kotlin theme={null}
val riveFile = rememberRiveFile(
RiveFileSource.RawRes.from(R.raw.my_rive_file),
riveWorker
)
when (riveFile) {
is Result.Loading -> {
// Show loading indicator
}
is Result.Failure -> {
// Show error message
}
is Result.Success -> {
Rive(riveFile.value)
}
}
```
The legacy runtime's convenience methods, e.g. `setRiveResource()`, do not provide a way to track loading state or handle errors directly. Instead, the file must first be loaded using the `File` class. Loading is normally synchronous, though could be performed on a background thread. With some effort similar loading state tracking could be implemented.
There are no plans to retrofit this feature into the legacy runtime.
### Rendering to a bitmap
The new runtime provides built-in support for [rendering Rive to an Android `Bitmap`](/docs/runtimes/advanced-topic/rendering-to-a-bitmap), which can be useful for scenarios such as snapshot testing or rendering video encoded from data-bound Rive files into image frames on the edge (i.e. the user's device). This is done using the `RenderBuffer` class or the `onBitmapAvailable` callback in the `Rive` Composable.
Rendering to a Bitmap is technically possible in the legacy runtime by rendering to a Canvas backed by a Bitmap or by sub-classing the renderer, but it is not a built-in feature and requires more effort to implement.
There are no plans to retrofit this feature into the legacy runtime.
### Updating a Data Bind unsettles the State Machine
In the new runtime, updating a data-bound property [automatically "unsettles" the state machine](/docs/runtimes/android/android#adding-rive-to-your-composition), causing it to advance and draw based on the new data. By comparison, the legacy runtime required you to call `RiveAnimationView.play()` after updating data-bound properties on a settled state machine to achieve the same effect.
We may consider retrofitting this behavior into the legacy runtime in the future as it is a common source of confusion. However, doing so would be a breaking change, and it may not be worth the disruption for existing users.
## Legacy exclusive features
Some features are only available in the legacy runtime. This is usually because they were less commonly used, were complex in practice, or were difficult to maintain and support. Below is a list of such features along with guidance on how to handle their absence in the new runtime.
### View-based API
The legacy runtime is built around the `RiveAnimationView` class, which is a subclass of Android's `TextureView` (and subsequently `View`). This makes it easy to integrate into existing View-based Android applications. The new runtime is currently Compose-based and does not provide a View subclass. If you need to use Rive in a View-based application, you will need to set up a Compose environment within your View hierarchy using `ComposeView`.
There are plans to provide a View-based API in the future.
### Frame metrics
The legacy runtime includes support for frame metrics, providing some rendering performance numbers and potentially helping to identify bottlenecks. This is done by enabling frame metrics collection on the `RiveAnimationView`.
```kotlin theme={null}
riveView.startFrameMetrics()
```
The new runtime does not yet include any comparable feature. Instead, you can use Android's built-in profiling tools, such as the Android Profiler in Android Studio, to measure rendering performance and identify bottlenecks.
We will be adding performance monitoring in the future. The specific form it takes is to be determined.
### CDN assets
**Legacy**
The Rive Editor allows marking an asset as "Hosted", meaning it is uploaded to Rive's CDN. The legacy runtime includes built-in support for loading these assets directly from the CDN when the Rive file is loaded. This is done automatically and by default when using the `RiveAnimationView` class.
**Legacy RiveAnimationView**
```kotlin theme={null}
// Builder API (enabled by default)
val riveView = RiveAnimationView.Builder(context)
.setResource(R.raw.my_rive_file)
.setShouldLoadCDNAssets(true)
.build()
// Using asset loader (enabled by default)
val riveView = RiveAnimationView(context)
riveView.setAssetLoader(FallbackAssetLoader(context, loadCDNAssets = true))
```
**Legacy XML Layout**
```xml theme={null}
```
**New**
The new runtime does not include built-in support for loading CDN assets.
We will be adding a new API in a future update to query the asset manifest for a file, which will include URLs for hosted assets. This will allow you to load them using standard networking libraries and supply them to the Rive worker using existing asset APIs.
### Setting a Rive file from network
The legacy runtime provides built-in support for loading Rive files from network URLs using the now defunct Volley library. This includes methods such as:
**Legacy Builder API**
```kotlin theme={null}
RiveAnimationView.Builder(context)
.setResource("https://example.com/animation.riv")
```
**Legacy XML Layout**
```xml theme={null}
```
The new runtime does not include this feature directly. Instead you can implement it using standard Android networking libraries (e.g., Retrofit, OkHttp) to fetch the file and then load it using a `RiveFileSource.Bytes` source, passing the downloaded bytes. This source can be supplied to `rememberRiveFile` when using Compose or `RiveFile.fromSource` when working outside of a Compose context.
We are considering adding built-in network loading capabilities in future releases. If implemented, it would not use Volley, preferring a modern alternative. It would also likely be opt-in to avoid adding unnecessary dependencies for users who do not need network loading.
### Rendering to canvas
> [card]
>
> See also Choose a Renderer for more details.
>
> [Open](/docs/runtimes/choose-a-renderer/overview#android)
The legacy runtime includes a Canvas renderer that allows rendering Rive animations directly into an Android `Canvas`. This was useful as a fallback for scenarios where the Rive Renderer wasn't yet feature compatible. As we have improved the Rive Renderer, this use case has diminished.
The Canvas renderer is enabled with the following APIs.
**Rive Global Default**
```kotlin theme={null}
Rive.defaultRendererType = RendererType.Canvas
```
**Legacy RiveAnimationView Builder**
```kotlin theme={null}
RiveAnimationView.Builder(context)
.setRendererType(RendererType.Canvas)
```
**Legacy XML Layout**
```xml theme={null}
```
The new runtime does not include a Canvas renderer, focusing instead on the Rive Renderer for optimal performance and feature support, such as vector feathering. Additionally, the Canvas renderer has limitations around performance and visual fidelity compared to the Rive Renderer.
There are no current plans to reintroduce Canvas rendering in the new runtime.
### Artboard volume
The legacy runtime can set an artboard's audio volume through the `Artboard.volume` property or `RiveAnimationView.setVolume()`. This feature is not present in the new runtime.
We may consider adding audio features in the future, but there are no immediate plans to do so.
### State Machine Inputs
> [card]
>
> See also the Inputs documentation for more details.
>
> [Open](/docs/runtimes/android/inputs)
The legacy runtime provides methods to set state machine inputs.
```kotlin theme={null}
riveView.setNumberState("My State Machine", "My Number Input", 42.0f)
riveView.setBooleanState("My State Machine", "My Boolean Input", true)
riveView.fireState("My State Machine", "My Trigger Input")
```
The new runtime does not include these methods. State machine inputs are deprecated in favor of data binding, which provides a more flexible and powerful way to manage changes to state machines.
The Rive Editor provides an automatic conversion tool in Menu > "Convert Inputs to ViewModels". This is a 1:1 conversion that preserves existing behavior while enabling the benefits of data binding, though this may not be ideal for performance or semantics. You can use this feature to perform initial migration when adopting the new runtime and then iterate on the data contract to improve it further.
### Events
> [card]
>
> See also the Rive Events documentation for more details.
>
> [Open](/docs/runtimes/android/rive-events)
The legacy runtime includes support for listening to Rive events to respond to events emitted from the Rive file. This is done through the `RiveFileController.Listener` interface.
```kotlin theme={null}
riveView.addEventListener(object : RiveFileController.RiveEventListener {
override fun notifyEvent(event: RiveEvent) {
// Handle event
}
})
```
The new runtime does not include this feature. Events are deprecated in favor of data binding, which provides a more flexible and powerful way to listen for changes from the Rive file. Simple events can be replaced with trigger properties in a view model.
There are no current plans to reintroduce event listening in the new runtime.
### Text Runs
> [card]
>
> See also the Text documentation for more details.
>
> [Open](/docs/runtimes/android/text)
The legacy runtime includes support for text runs, used to get and set dynamic text in Rive content.
```kotlin theme={null}
val text = riveView.getTextRunValue("My Text Run")
riveView.setTextRunValue("My Text Run", "Hello, World!")
```
The new runtime does not include this feature. Text runs are deprecated in favor of data binding, which provides a more flexible and powerful way to manage dynamic text content through string properties. Any text run which was previously addressed by name must instead be bound to a string property in a view model.
```kotlin theme={null}
val vmi = rememberViewModelInstance(riveFile)
// Collect from flow
val text by vmi.getStringFlow("My Text Property").collectAsState(initial = "")
// Or get imperatively
LaunchedEffect(vmi) {
val text = vmi.getStringFlow("My Text Property").first()
}
vmi.setString("My Text Property", "Hello, World!")
```
There are no current plans to reintroduce text run support in the new runtime.
### Linear animations
> [card]
>
> See also the Linear Animation documentation for more details.
>
> [Open](/docs/runtimes/android/animation-playback)
In the Rive Editor's [animate mode](/docs/editor/fundamentals/design-vs-animate-mode), designers can create both state machines and linear animations. The legacy Android runtime supports playing multiple linear animations directly allowing developers to trigger these animations without using state machines. These included loop modes, direction, duration, and seeking.
**Legacy Kotlin Methods**
```kotlin theme={null}
// Query the list of linear animation names
val linearAnimations = riveView.animations
// Query the playing animations
val playingAnimations = riveView.playingAnimations
// Play a linear animation from the Builder API
RiveAnimationView.Builder(context)
.setResource(R.raw.my_rive_file)
.setAnimationName("My Animation")
// Play a linear animation using the set method
riveView.setRiveResource(R.raw.my_rive_file, animationName = "My Animation")
// Play a linear animation directly
riveView.play("My Animation")
```
**Legacy XML Layout**
```xml theme={null}
```
In practice, working with linear animations is more granular and brittle compared to state machines, and as such they are not directly supported in the new runtime. To achieve similar functionality, you can create a state machine in the Rive Editor that plays the desired linear animation and then trigger that state machine from your Android code.
There are no current plans to reintroduce direct linear animation playback in the new runtime.
### Multiple State Machines per view
The legacy runtime allows multiple state machines to be associated with a single `RiveAnimationView` instance. At the core runtime level there is no technical limitation, and each state machine is processed in sequence. In practice this leads to complexity and difficulty reasoning about state, especially when data binding is involved. Only the Android legacy runtime supported this capability among the various Rive runtimes.
The new runtime enforces a one-to-one relationship between Rive instances and state machines to simplify state management. If you need to manage concurrent, overlapping states, consider using [state machine layers](/docs/editor/state-machine/state-machine#layers).
There are no current plans to reintroduce multiple state machines per Rive instance in the new runtime.
### Observing State Machine state
The legacy runtime provides methods to observe which state is currently active in a state machine. This can be useful for triggering actions in your application based on the current state of the animation.
```kotlin theme={null}
riveView.registerListener(object : RiveFileController.Listener {
override fun notifyStateChanged(stateMachineName: String, stateName: String) {
// Handle state change
}
})
```
The new runtime does not include this feature. The original feature was added before data binding and is brittle to Rive file changes. The modern equivalent is through data binding properties emitting values when the state changes. This means looser coupling to the Rive file and allows designers to iterate without breaking the application code.
There are no current plans to reintroduce state observation in the new runtime.
### Single touch support
The legacy runtime supports single touch input, allowing only one touch interaction at a time. This is to maintain backwards compatibility with existing Rive files that were designed with single touch in mind. As such it is also the default behavior.
**Legacy RiveAnimationView**
```kotlin theme={null}
// Builder API
val riveView = RiveAnimationView.Builder(context)
.setMultiTouchEnabled(false)
.build()
// Property
riveView.multiTouchEnabled = false
```
**Legacy XML Layout**
```xml theme={null}
```
The new runtime supports only multitouch input. In practice, Rive files should rarely need to distinguish between single and multitouch, as touch points are typically used to trigger interactions rather than being tracked individually. Test your Rive files when migrating to ensure they behave as expected with multitouch input, and adjust the design if necessary.
There are no current plans to reintroduce single touch support in the new runtime.
### Getting by index
The legacy runtime provides methods to get artboards, animations state machines, view models, and view model instances by their index in addition to their name. This is rarely useful in scenarios where you want to iterate over all elements.
```kotlin theme={null}
val artboard = riveFile.artboard(0)
val animation = artboard.animation(0)
val stateMachine = artboard.stateMachine(0)
val viewModel = riveFile.getViewModelByIndex(0)
val instance = viewModel.createInstanceFromIndex(0)
```
The new runtime can achieve similar functionality by iterating over queried names. For artboards, for example:
```kotlin theme={null}
LaunchedEffect(riveFile) {
val artboardNames = riveFile.getArtboardNames()
for (name in artboardNames) {
Artboard.fromFile(riveFile, name).use {
// Use artboard
}
}
}
```
There are no current plans to reintroduce getting by index in the new runtime.
### Renderer class
The legacy runtime includes the `Renderer` and `RiveArtboardRenderer` classes that allow you to override rendering behavior for Rive. It is difficult to use correctly, ensure proper life cycles, and maintain compatibility with the Rive Renderer as it evolves.
The new runtime does not include a `Renderer` class, focusing instead on the most common use cases. Other use cases, such as rendering to an Android Bitmap, are supported through dedicated APIs. Render loops are managed by the `Rive` Composable and execute on the `RiveWorker`.
There are no current plans to reintroduce a Renderer class in the new runtime.
### Controller class
The legacy runtime includes a `RiveFileController` class that provides methods to control playback, manage state machines, and observe state changes. It is tightly coupled to the `RiveAnimationView`.
The new runtime does not need a separate controller class, as control is provided directly through the `Rive` Composable and associated helpers.
There are no current plans to reintroduce a Controller class in the new runtime.
# Playing Audio
Source: https://rive.app/docs/runtimes/android/playing-audio
Playing Rive audio events
To learn more on how to add audio to your Rive file, see [Audio Events](/docs/editor/events/audio-events).
## Embedded assets
Embedded assets require no additional work to play audio.
## Referenced assets
Referenced assets require a little bit more work to play audio. Audio will still automatically play, but the audio file(s) must be loaded when a Rive runtime attempts to play audio.
For more information, see [Loading Assets](/docs/runtimes/android/loading-assets).
# Rendering to a Bitmap
Source: https://rive.app/docs/runtimes/android/rendering-to-a-bitmap
Render screenshots and video at runtime.
Rendering to a bitmap at runtime is useful for scenarios such as snapshot testing and rendering video encoded from data-bound files.
> [!NOTE]
>
> For rendering to a bitmap from the Rive Editor, see [Exporting for Video or Static Design](/docs/editor/exporting/exporting-for-video-and-static-design).
> [tab] Compose
>
> > [card] [Demo](https://github.com/rive-app/rive-android/blob/master/app/src/main/java/app/rive/runtime/example/RiveSnapshotActivity.kt)
> >
> > See the `RiveSnapshotActivity` example for a demonstration of this feature.
>
> Rendering to a bitmap is done using the `RenderBuffer` class or the `onBitmapAvailable` callback in the `Rive` Composable.
> [tab] Legacy
>
> Rendering to a bitmap was technically possible in the legacy runtime by rendering to a Canvas backed by a bitmap or by sub-classing the renderer, but it was not a built-in feature and required more effort to implement. There are no plans to retrofit this feature into the legacy runtime.
# State Machine Playback
Source: https://rive.app/docs/runtimes/android/state-machines
Playing a state machine
For more information on designing and building state machines in the Rive editor, please refer to [State Machine Overview](/docs/editor/state-machine).
A Rive state machine is a set of animation states and the transitions between them. At runtime there is limited ability to observe or modify the state directly. This is by design, as this would limit the ability of a designer in Rive to modify the state machine without creating breaking changes. Instead, state machines are indirectly controlled through transitions conditioned on [Data Binding](data-binding) properties.
A designer assigns a default state machine for each artboard in the Rive editor. They may create multiple state machines, each representing a different configuration of states and transitions. When rendering a Rive file and artboard, you may choose which state machine to play. If no state machine is specified, the default state machine for that artboard is used.
## Controlling playback
State machines play by "advancing" over time. This is done once per frame by the amount of time between frames. For example, for a graphic running at 60 frames per second, the state machine would be advanced by approximately 16.67 milliseconds (1/60th of a second) each frame. This advancing evaluates keyframes, transitions, data bindings changes, and ultimately the visible artboard elements to create the illusion of motion over time.
This runtime provides a way to control whether the state machine is playing. When paused or stopped, the state machine does not advance and the last rendered frame remains visible. When playing from pause, the state machine resumes from where it left off, whereas when playing from stop, it restarts from the entry state.
In addition to the paused/stopped state, state machines may also "settle". This is an optimization where the Rive runtime detects that no further changes will occur (for example, if there are no active transitions or animations). While settled the state machine will also stop advancing. This improves performance and energy use by avoiding unnecessary calculations. State machines are unsettled by external actions that change their state, such as user input or data binding changes. You can additionally force a state machine to unsettle by calling play, though it may immediately re-settle if there is no further work to be done.
## Playing State Machines
> [tab] Compose
>
> By default, the `Rive` composable will select and create the default state machine specified in the Rive editor. To specify a different state machine, you must first create a `StateMachine` object from an `Artboard`.
>
> ### Compose
>
> State machine objects can be created in Compose using the `rememberStateMachine` function, which takes an artboard and name of the state machine.
>
> ```kotlin theme={null}
> val artboard = rememberArtboard(myRiveFile, "My Artboard")
> val stateMachine = rememberStateMachine(artboard, "My State Machine")
> ```
>
> ### Outside of Compose
>
> Alternatively, you can create a state machine outside of Compose contexts. Note that with this approach you are responsible for managing the state machine's lifecycle and must eventually close it with `StateMachine::close()` when no longer needed, or leveraging its [`AutoClosable`](https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-auto-closeable.html) interface with a `use` block.
>
> ```kotlin theme={null}
> val artboard = Artboard.fromFile(myRiveFile, "My Artboard")
> val stateMachine = StateMachine.fromArtboard(artboard, "My State Machine")
> ...
> stateMachine.close()
> artboard.close()
> ```
>
> ### Using the State Machine
>
> Once you have a state machine, you can pass it to the `Rive` composable via the `stateMachine` parameter.
>
> By default the Rive composable will play the selected state machine. To toggle the play/pause state, set the `playing` parameter, triggering a re-composition. This is also used to replicate the auto-play behavior of other runtimes - simply set `playing` to false if you need to perform initial setup and set to true once ready.
>
> ```kotlin theme={null}
> Rive(
> myRiveFile,
> artboard = artboard,
> stateMachine = stateMachine,
> playing = true // Or false to pause
> )
> ```
> [tab] Legacy
>
> By default RiveAnimationView will auto-play the selected state machine.
>
> ⚠️ The legacy API allows for playing multiple linear animations and state machines simultaneously. This is discouraged due to complexity and divergence from other runtimes. Prefer to use a single state machine controlling all animation through states and transitions.
>
> ### Using XML Layouts
>
> ```xml theme={null}
> app:riveResource="@raw/my_rive_file"
> app:riveStateMachine="My State Machine"
> app:riveAutoPlay="true" />
> ```
>
> ### Using Kotlin
>
> ```kotlin theme={null}
> animationView.setRiveResource(
> R.raw.my_rive_file,
> stateMachineName = "My State Machine",
> autoplay = true
> )
> ```
>
> ### Controlling Playback
>
> You can control the state machine's playing state using the same APIs as those for linear animation playback (i.e. `play`, `pause`, and `stop`). When doing so, ensure you set the `isStateMachine` parameter to `true`.
>
> ```kotlin theme={null}
> animationView.play("My State Machine", isStateMachine = true)
> animationView.pause("My State Machine", isStateMachine = true)
> animationView.stop("My State Machine", isStateMachine = true)
> ```
# Apple
Source: https://rive.app/docs/runtimes/apple/apple
Apple runtime for Rive.
> [!WARNING]
>
> Note that certain Rive features may not be supported yet for a particular runtime, or may require using the Rive Renderer.
>
> For more details, refer to the [feature support](/docs/feature-support/) and [choosing a renderer](/docs/runtimes/choose-a-renderer/) pages.
## Overview
This guide documents how to get started using the Apple runtime library. Rive runtime libraries are open-source. The source is available in its [GitHub repository](https://github.com/rive-app/rive-ios).
This library contains an API for Apple apps to easily integrate their Rive assets for both UIKit/AppKit and SwiftUI. The runtime can be installed via Cocoapods or Swift Package Manager.
The Apple runtime currently supports iOS 14.0+, visionOS 1.0+, tvOS 16.0+, macOS 13.1+, and Mac Catalyst 14.0+
The new Apple runtime is designed as a Swift-first API leveraging Swift Concurrency, with improved multi-threading support for Rive.
The entry point is the `Rive` type, which is a container for the configuration of a Rive view. This includes the file, artboard, state machine, fit, and background color.
Adding a Rive view is done by creating a `RiveUIView` with a `Rive` object, and then adding it to the view hierarchy. In SwiftUI, this is as easy as calling `.view()` on a `RiveUIView` object.
It is important to note that while multi-threading is supported, the calls from Rive objects must still be made on the main thread. This is enforced at compile time by marking functions and types as `@MainActor`.
Most APIs are marked as `throws`, with `Error` types available for the different Rive primitives.
## Getting started
Follow the steps below for a quick start on integrating Rive into your Apple app.
> [tab] New Runtime
>
> **1. Install the Runtime**
>
> With CocoaPods going into [maintenance mode](https://blog.cocoapods.org/CocoaPods-Support-Plans/), we recommend using Swift Package Manager.
>
> To install via Xcode, you can follow Apple's instructions for [adding a package dependency to your app](https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app), with the Apple runtime's GitHub URL: [https://github.com/rive-app/rive-ios](https://github.com/rive-app/rive-ios).
>
> Alternatively, you can add the dependency manually by adding the following to your `Package.swift` file:
>
> ```swift theme={null}
> dependencies: [
> .package(url: "https://github.com/rive-app/rive-ios", from: "6.24.0")
> ]
> ```
>
> Then add the dependency to your target:
>
> ```swift theme={null}
> targets: [
> .target(
> name: "MyApp",
> dependencies: [
> .product(name: "RiveRuntime", package: "rive-ios")
> ]
> )
> ]
> ```
>
> **2. Import Rive**
>
> The new Apple runtime is available in the same Swift package and CocoaPods pod as the legacy runtime. Both runtime APIs are available in the same package, so you can import the runtime using the same import statement.
>
> ```swift theme={null}
> import RiveRuntime
> ```
>
> **3. Create a Worker**
>
> A `Worker` is what handles concurrency in the Rive runtime. This type handles starting a background thread for processing, in addition to handling global (out-of-band) assets.
>
> A `Worker` must be alive for the duration of Rive usage. A `File` creates a strong reference to a `Worker`, so a `Worker` will at least be alive for the duration of use of a `File`, unless a reference to a `Worker` is kept outside of a file.
>
> ```swift theme={null}
> // In an async context
> // GPU Canvas is required for 3D content.
> let worker = try await Worker(
> configuration: .init(enableGPUCanvas: true)
> )
> ```
>
> See [GPU Canvas](/docs/runtimes/apple/gpu-canvas) for more information about this worker configuration.
>
> For more information on threading, see [Threading](#threading).
>
> **4. Load a File**
>
> Once you have created a `Worker`, you can move onto creating a `File`. Each `File` object takes a source and a worker.
>
> > [!NOTE]
> >
> > The `File` initializer is marked `@MainActor`.
>
> ```swift Local File theme={null}
> let worker = try await Worker(
> configuration: .init(enableGPUCanvas: true)
> )
> let file = try await File(source: .local("my_file", Bundle.main), worker: worker)
> ```
>
> ```swift Remote URL theme={null}
> let worker = try await Worker(
> configuration: .init(enableGPUCanvas: true)
> )
> let url: URL = URL(string: "https://example.com/my_file.riv")!
> let file = try await File(source: .url(url), worker: worker)
> ```
>
> ```swift Data theme={null}
> let worker = try await Worker(
> configuration: .init(enableGPUCanvas: true)
> )
> let data: Data = ...
> let file = try await File(source: .data(data), worker: worker)
> ```
>
> For large files where you only use some of the artboards, you can decode each artboard the first time it's used instead of while the file loads. See [Deferred File Loading](/docs/runtimes/apple/deferred-file-loading).
>
> **5. Add a View**
>
> Once you have created a `File`, you can move onto creating a `Rive` object. This object defines the configuration of a view. The most basic implementation is created with just a file; Rive will handle loading the default artboard and state machine for rendering. Additionally, if the artboard contains a default view model instance, it will be bound to the state machine automatically.
>
> Once you have created a `Rive` object, you can initialize your view. In UIKit, this is done by creating a `RiveUIView` and adding it to the view hierarchy. In SwiftUI, this is done by using the `RiveUIViewRepresentable` and `AsyncRiveUIViewRepresentable` types.
>
> ```swift UIKit theme={null}
> let riveView = RiveUIView(rive: {
> let worker = try await Worker(
> configuration: .init(enableGPUCanvas: true)
> )
> let file = try await File(source: .local("my_file", Bundle.main), worker: worker)
> return try await Rive(file: file)
> })
> view.addSubview(riveView)
> ```
>
> ```swift SwiftUI theme={null}
> var body: some View {
> // After having created a `Rive` object, you can initialize your view.
> RiveUIViewRepresentable(rive: rive)
> }
> ```
>
> ```swift SwiftUI (Async) theme={null}
> var body: some View {
> // After having created a `Rive` object, you can initialize your view.
> AsyncRiveUIViewRepresentable {
> let worker = try await Worker(
> configuration: .init(enableGPUCanvas: true)
> )
> let file = try await File(source: .local("my_file", Bundle.main), worker: worker)
> return try await Rive(file: file)
> }
> }
> ```
>
> The above example uses the default artboard and state machine for the file, binding authored main and global view model defaults to the state machine when available. This is the default behavior when initializing a `Rive` object without specifying an artboard or state machine.
>
> Alternatively, you can also specify which artboard and state machine to use. Documentation and examples for manually selecting which artboard to use is available in the [Artboards](/docs/runtimes/apple/artboards#choosing-an-artboard) documentation. Documentation and examples for manually selecting which state machine to use is available in the [State Machines](/docs/runtimes/apple/state-machines#getting-a-state-machine) documentation.
>
> **6. Data Binding**
>
> [Data Binding](/docs/runtimes/apple/data-binding) is a feature that allows you to dynamically update your Rive graphics from code. This includes things such as strings, numbers, booleans, and more.
>
> `Rive(file:)` creates a state machine and binds authored main and global defaults when available. For property access, create and retain the instances yourself:
>
> ```swift theme={null}
> let artboard = try await file.createArtboard()
> let viewModelInstance = try await file.createViewModelInstance(
> .viewModelDefault(from: .artboardDefault(artboard))
> )
> let stateMachine = try await artboard.createStateMachine(binding: viewModelInstance)
> let rive = try await Rive(file: file, artboard: artboard, stateMachine: stateMachine)
> ```
>
> Store `viewModelInstance` in your app's model. The state machine has no instance getters, and the deprecated `rive.viewModelInstance` getter returns `nil` with these initializers. See [Global View Models](/docs/runtimes/apple/data-binding#global-view-models) for shared bindings and [setup recipe](/docs/runtimes/apple/migrating-from-legacy#setting-up-instances-for-your-app) for creating and retaining instances in your app.
>
> Once data binding is set up, you can update and listen to data binding properties at runtime.
>
> ```swift Set Values theme={null}
> // Use the viewModelInstance retained during setup.
> let stringProperty = StringProperty(path: "path/to/string")
> viewModelInstance.setValue(of: stringProperty, to: "Hello, Rive")
> ```
>
> ```swift Get Values theme={null}
> // Use the viewModelInstance retained during setup.
> let stringProperty = StringProperty(path: "path/to/string")
>
> // Get the current value of the property
> let value = try await viewModelInstance.value(of: stringProperty)
>
> // Get a stream of values for the property, which emits a new value whenever the property changes.
> let valueStream = viewModelInstance.valueStream(of: stringProperty)
> do {
> for try await value in valueStream {
> print(value)
> }
> } catch let error as ViewModelInstanceError {
> print(error)
> } catch {
> print(error)
> }
> ```
>
> **7. Examples**
>
> For basic usage, see the [Marty](https://github.com/rive-app/rive-ios/blob/main/Example-iOS/Source/Examples/Concurrency/MartyView.swift) example in our Example app.
>
> For a more complete example, see the [Quick Start](https://github.com/rive-app/rive-ios/blob/main/Example-iOS/Source/Examples/Concurrency/QuickStartView.swift) example in our Example app, which demonstrates how to use data binding.
>
> For examples on how to pause and resume animations, as well as set frame rate, see the [Player](https://github.com/rive-app/rive-ios/blob/main/Example-iOS/Source/Examples/Concurrency/PlayerView.swift) example in our Example app.
> [tab] Legacy Runtime
>
> **1. Install the Runtime**
>
> **Swift Package Manager**
>
> To install via Swift Package Manager, in the package finder in Xcode, search for `rive-ios` or the full Github path: `https://github.com/rive-app/rive-ios`
>
> **Cocoapods**
>
> Add the following to your Podspec file:
>
> ```bash theme={null}
> pod 'RiveRuntime'
> ```
>
> **2. Import Rive**
>
> Add the following to the top of your file where you utilize the Rive runtime:
>
> ```swift theme={null}
> import RiveRuntime
> ```
>
> **3. Usage**
>
> The primary object you'll use is a `RiveViewModel`. It is responsible for creating and interacting with Rive assets.
>
> > [tab] SwiftUI
> >
> > ```swift Local File theme={null}
> > struct AnimationView: View {
> > var body: some View {
> > RiveViewModel(fileName: "cool_rive_animation").view()
> > }
> > }
> > ```
> >
> > ```swift Remote URL theme={null}
> > struct AnimationView: View {
> > var body: some View {
> > RiveViewModel(
> > webURL: "https://cdn.rive.app/animations/off_road_car_v7.riv"
> > ).view()
> > }
> > }
> > ```
>
> > [tab] UIKit
> >
> > You can add Rive to a view controller purely with code by making the `RiveViewModel`, telling it to create a fresh `RiveView` and then adding it to the view hierarchy.
> >
> > Alternatively, you can add Rive to a controller using Storyboards by making a `RiveViewModel`, and setting its view to be the `RiveView` you made in the Storyboard.
> >
> > ```swift Programmatic theme={null}
> > class AnimationViewController: UIViewController {
> > var simpleVM = RiveViewModel(fileName: "cool_rive_animation")
> >
> > override func viewWillAppear(_ animated: Bool) {
> > let riveView = simpleVM.createRiveView()
> > view.addSubview(riveView)
> > riveView.frame = view.bounds
> > }
> > ```
> >
> > ```swift Storyboard theme={null}
> > class AnimationViewController: UIViewController {
> > @IBOutlet weak var riveView: RiveView!
> > var simpleVM = RiveViewModel(fileName: "cool_rive_animation")
> >
> > override public func viewDidLoad() {
> > simpleVM.setView(riveView)
> > }
> > }
> > ```
## Playing / pausing
> [tab] New Runtime
>
> ```swift UIKit theme={null}
> let rive = try await Rive(...)
> let riveView = RiveUIView(rive: rive)
> riveView.isPaused = true // or false to resume
> ```
>
> ```swift SwiftUI theme={null}
> @State var isPaused = false
> var body: some View {
> RiveUIViewRepresentable(rive: rive)
> .paused(isPaused)
> }
> ```
>
> ```swift SwiftUI (Async) theme={null}
> @State var isPaused = false
> var body: some View {
> AsyncRiveUIViewRepresentable {
> let worker = try await Worker()
> let file = try await File(source: ..., worker: worker)
> let rive = try await Rive(file: file)
> return rive
> }
> .paused(isPaused)
> }
> ```
> [tab] Legacy Runtime
>
> ```swift theme={null}
> let viewModel = RiveViewModel(fileName: "...")
> viewModel.pause() // or play() to resume
> ```
## Frame rate
> [tab] New Runtime
>
> ```swift UIKit theme={null}
> let rive = try await Rive(...)
> let riveView = RiveUIView(rive: rive)
> // Set a fixed frame rate
> riveView.frameRate = .fps(30)
> // Set a range of frame rates (Note: on < iOS 15 / macOS 14, this is the same as using .fps)
> riveView.frameRate = .range(minimum: 30, maximum: 60)
> // Revert to the default frame rate
> riveView.frameRate = .default
> ```
>
> ```swift SwiftUI theme={null}
> var body: some View {
> RiveUIViewRepresentable(rive: rive)
> .frameRate(.fps(30))
> // or
> .frameRate(.range(minimum: 30, maximum: 60))
> // or
> .frameRate(.default)
> }
> ```
>
> ```swift SwiftUI (Async) theme={null}
> var body: some View {
> AsyncRiveUIViewRepresentable {
> let worker = try await Worker()
> let file = try await File(source: ..., worker: worker)
> let rive = try await Rive(file: file)
> return rive
> }
> .frameRate(.fps(30))
> // or
> .frameRate(.range(minimum: 30, maximum: 60))
> // or
> .frameRate(.default)
> }
> ```
> [tab] Legacy Runtime
>
> ```swift theme={null}
> let viewModel = RiveViewModel(fileName: "...")
> viewModel.setPreferredFramesPerSecond(preferredFramesPerSecond: 30)
> // or, on iOS >= 15 / macOS >= 14
> viewModel.setPreferredFrameRateRange(preferredFrameRateRange: CAFrameRateRange(minimum: 30, maximum: 60))
> ```
## Semantics
Rive views can expose [semantics defined in the editor](/docs/editor/accessibility/semantics) to VoiceOver. Semantics are available in the New Runtime only.
See [Semantics](/docs/runtimes/apple/semantics) for the available modes and more detail.
## Native focus
With the Swift Concurrency API, graphics with authored focus nodes can participate in [native focus navigation](/docs/runtimes/apple/focus#native-focus). To send hardware-keyboard input to a graphic without the user first tabbing into it, see [Requesting keyboard input](/docs/runtimes/apple/focus#requesting-keyboard-input).
## Threading
> [tab] New Runtime
>
> The new runtime supports multi-threading through the introduction of `Worker` objects.
>
> ```swift theme={null}
> // In an async context
> let worker = try await Worker()
> let file = try await File(source: ..., worker: worker)
> ```
>
> The `Worker` object is responsible for creating and managing the background thread for the Rive instance.
>
> Each worker shares global out-of-band assets, such as images, fonts, and audio. Query a file with `File.getAssets()` and register a replacement on its worker using the asset's `uniqueName`. The replacement applies to matching assets in files using that worker, including files already loaded and files loaded later. See [Loading Assets](/docs/runtimes/apple/loading-assets) for examples.
>
> One worker roughly equates to one background thread. If you are rendering multiple heavy Rive graphics, you can create one `Worker` per file to have each processed on its own background thread.
>
> The number of `Worker` objects is limited by system availability; specifically, a `Worker` is backed by a `DispatchQueue`, which handles the creation and reuse of threads.
>
> It is important to note that while multi-threading is supported, Rive object API calls must still be made on the main actor. This is enforced at compile time with functions and types marked as `@MainActor`.
>
> ### Shared Workers
>
> To share out-of-band or referenced assets across multiple `File` objects, use a shared `Worker`. An example implementation is shown below.
>
> > [!NOTE]
> >
> > `AsyncShared` and the `Worker` extensions below are application-level helpers. They are not included with `RiveRuntime`.
>
> ```swift AsyncShared.swift theme={null}
> /// Lazily creates and caches a value. Failed initialization can be retried.
> @MainActor
> final class AsyncShared {
> private let makeValue: @MainActor () async throws -> Value
> private var cachedValue: Value?
> private var loadingTask: Task?
>
> init(_ makeValue: @escaping @MainActor () async throws -> Value) {
> self.makeValue = makeValue
> }
>
> func value() async throws -> Value {
> if let cachedValue {
> return cachedValue
> }
>
> let task = loadingTask ?? Task {
> defer { loadingTask = nil }
> let value = try await makeValue()
> cachedValue = value
> return value
> }
> loadingTask = task
>
> return try await task.value
> }
> }
> ```
>
> ```swift AsyncShared+Worker.swift theme={null}
> import RiveRuntime
>
> extension AsyncShared where Value == Worker {
> convenience init(configuration: Worker.Configuration = .init()) {
> self.init {
> try await Worker(configuration: configuration)
> }
> }
> }
>
> extension Worker {
> @MainActor
> private static let sharedWorker = AsyncShared()
>
> @MainActor
> private static let sharedGPUCanvasWorker = AsyncShared(
> configuration: .init(enableGPUCanvas: true)
> )
>
> @MainActor
> static func shared() async throws -> Worker {
> try await sharedWorker.value()
> }
>
> @MainActor
> static func sharedGPUCanvas() async throws -> Worker {
> try await sharedGPUCanvasWorker.value()
> }
> }
> ```
>
> Then, when creating a `Rive` object, use `Worker.shared()` to get the shared worker.
>
> ```swift theme={null}
> let worker = try await Worker.shared()
> let file = try await File(source: ..., worker: worker)
> let rive = try await Rive(file: file)
> ```
> [tab] Legacy Runtime
>
> The legacy runtime is currently single-threaded on the main thread. This means that all Rive calls must be made on the main thread. It is recommended that if you are on a background thread, you should dispatch to the main queue before making any Rive calls.
## Logging
> [tab] New Runtime
>
> The new runtime does not yet include logging, but will be added in the near future.
> [tab] Legacy Runtime
>
> Enabling logging is as simple as setting `RiveLogger.isEnabled` to `true`.
>
> ```swift theme={null}
> RiveLogger.isEnabled = true
> ```
>
> For more details on logging levels, categories, and verbose logs, see the [Logging](/docs/runtimes/logging) page.
>
> See subsequent runtime pages to learn how to control animation playback, state machines, and more.
## Example app
You can run our Apple example app from the Rive GitHub repository.
```bash theme={null}
git clone https://github.com/rive-app/rive-ios
```
Open the `Example-iOS` app in Xcode and be sure to select the `Preview (iOS)` or `Preview (macOS)` [scheme](https://developer.apple.com/documentation/xcode/customizing-the-build-schemes-for-a-project). The other schemes are for development purposes and require additional configuration, see[ ](https://github.com/rive-app/rive-ios/blob/main/CONTRIBUTING.md)[CONTRIBUTING.MD](https://github.com/rive-app/rive-ios/blob/main/CONTRIBUTING.md).

## Resources
GitHub: [https://github.com/rive-app/rive-ios](https://github.com/rive-app/rive-ios)
Examples:
* [https://github.com/rive-app/rive-ios/tree/main/Example-iOS](https://github.com/rive-app/rive-ios/tree/main/Example-iOS)
* [https://github.com/rive-app/rive-ios/tree/main/Demo-App](https://github.com/rive-app/rive-ios/tree/main/Demo-App)
* Free course from Meng To: [https://designcode.io/swiftui-rive](https://designcode.io/swiftui-rive)
# Artboards
Source: https://rive.app/docs/runtimes/apple/artboards
Selecting which artboard to render at runtime
For more information on creating artboards in the Rive editor, please refer to [Artboards](/docs/editor/fundamentals/artboards).
## Choosing an Artboard
When a Rive object is instantiated or when a Rive file is rendered, you can specify the artboard to use. If no artboard is given, the [default artboard](/docs/editor/fundamentals/artboards#default-state-machine), as set in the Rive editor, is used. If no default artboard is set, the first artboard is used.
Only one artboard can be rendered at a time.
> [tab] New Runtime
>
> The following section assumes that you have read through the [Apple](/docs/runtimes/apple/apple) overview.
>
> ### Getting an Artboard
>
> Once you have created a `File`, you can then retrieve information for and create `Artboard` types.
>
> ```swift theme={null}
> // Get all artboard names in the file
> let artboardNames = try await file.getArtboardNames()
> // Get the default artboard for the file
> let defaultArtboard = try await file.createArtboard()
> // Get an artboard by name from the file
> let artboardByName = try await file.createArtboard("Artboard")
> ```
>
> Note that these are all async throwing functions marked as `@MainActor`. Since they are functions called on a `File` object, any thrown errors will be of type `FileError`.
>
> An example of when one of these functions will throw is if you call `.createArtboard(_:)` with a name that is not in the origin `File`, which will throw a `FileError.invalidArtboard(String)`.
>
> ### Using an Artboard
>
> Remember that the Rive configuration for a view is the `Rive` type. In the overview, we show initializing a `Rive` object with a file, opting to use the default artboard and state machine. However, you can initialize a `Rive` object with a specific artboard:
>
> ```swift theme={null}
> let worker = try await Worker()
> let file = try await File(source: .local("my_file", Bundle.main), worker: worker)
> let artboardByName = try await file.createArtboard("Artboard")
> let rive = try await Rive(file: file, artboard: artboardByName)
> ```
>
> Artboards then become the source of truth for state machines. See [State Machine](/docs/runtimes/apple/state-machines) for more details.
> [tab] Legacy Runtime
>
> **SwiftUI**
>
> ```swift theme={null}
> struct AnimationView: View {
> var body: some View {
> RiveViewModel(
> fileName: "my_rive_file",
> artboardName: "My Artboard"
> ).view()
> }
> }
> ```
>
> **UIKit**
>
> ```swift theme={null}
> class AnimationViewController: UIViewController {
> @IBOutlet weak var riveView: RiveView!
>
> var bananaVM = RiveViewModel(
> fileName: "my_rive_file",
> artboardName: "My Artboard",
> )
>
> override func viewDidLoad() {
> bananaVM.setView(riveView)
> }
> }
> ```
# Caching a Rive File
Source: https://rive.app/docs/runtimes/apple/caching-a-rive-file
Under most circumstances a `.riv` file should load quickly and managing the `RiveFile` yourself is not necessary. But if you intend to use the same `.riv` file in multiple parts of your application, or even on the same screen, it might be advantageous to load the file once and keep it in memory.
## Example usage
> [tab] New Runtime
>
> To cache a Rive file, you can create a strong reference to a `File` object. This `File` can then be reused to create `Rive` objects.
>
> Artboards and state machines are unique when created using the `create` functions. This means that you can create a new `Rive` object with the same file, but with different (and unique) artboards and state machines.
>
> ```swift theme={null}
> // An example builder class that creates a new Rive object with a cached file, creating new and unique artboards and state machines for each Rive object.
> class RiveBuilder {
> private let file: File
>
> init(file: File) {
> self.file = file
> }
>
> @MainActor
> func createRive(artboard: String? = nil, stateMachine: String? = nil) async throws -> Rive {
> let artboardInstance = try await file.createArtboard(artboard ?? .default)
> let stateMachineInstance = try await artboardInstance.createStateMachine(stateMachine ?? .default)
> return try await Rive(file: file, artboard: artboardInstance, stateMachine: stateMachineInstance)
> }
> }
>
> // Load and cache the file once
> let worker = try await Worker()
> let file = try await File(source: ..., worker: worker)
>
> // Create a builder with the cached file
> let builder = RiveBuilder(file: file)
>
> // Create multiple Rive objects with different configurations
> // Each Rive object is unique, but they all share the same cached File
> let rive1 = try await builder.createRive() // Creates a unique artboard and state machine
> let rive2 = try await builder.createRive() // Creates a unique artboard and state machine, behaving separately from the first Rive object
> let rive4 = try await builder.createRive(artboard: "MainArtboard", stateMachine: "Walking") // Creates a unique artboard and state machine, behaving separately from the first three Rive objects
> let rive5 = try await builder.createRive(artboard: "MainArtboard", stateMachine: "Idle") // Creates a unique artboard and state machine, behaving separately from the first four Rive objects
> ```
> [tab] Legacy Runtime
>
> ```swift theme={null}
> // Cache a RiveFile somewhere to cache for reuse
> let file = try! RiveFile(resource: "file", loadCdn: false)
>
> // For example purposes, a type that reuses a single RiveFile
> // when creating new view models for given state machines or artboards.
> class ViewModelGenerator {
> /// The RiveFile to reuse when generating new view models.
> private let file: RiveFile
>
> init(file: RiveFile) {
> self.file = file
> }
>
> // Returns a new view model using a cached RiveFile.
> // This means that the RiveFile will not have to be reparsed
> // each time a view model is generated.
> func viewModel(stateMachine: String?, artboard: String?) -> RiveViewModel {
> // While one RiveFile can be cached and reused, each view model
> // should have its own model as to not share state.
> let model = RiveModel(riveFile: file)
> return RiveViewModel(model, stateMachineName: stateMachine, artboardName: artboard)
> }
> }
> ```
>
> When using the `RiveViewModel(fileName:)` initializer, the Apple runtime does not cache file usage; that has to be handled manually. You may find that when reusing the same file, your memory usage increases (over time) as you create more view models. This is when you should consider caching the underlying file for reuse.
>
> Reusing a single `RiveFile` (when applicable) will reduce the overall memory usage of your application. If your `.riv` can be reused across multiple views, where each view requires the same file but uses different artboards or state machines, consider caching the `RiveFile` before creating your view models. While one `RiveFile` can be cached, to ensure that each view is in its own state, you must create a unique `RiveModel` per `RiveViewModel` instance.
# Data Binding
Source: https://rive.app/docs/runtimes/apple/data-binding
Connect your code to bound editor elements using View Models
Before engaging with the runtime data binding APIs, it is important to familiarize yourself with the core concepts presented in the [Overview](/docs/editor/data-binding/overview).
# View Models
View models describe a set of properties, but cannot themselves be used to get or set values - that is the role of [view model instances](#view-model-instances).
To begin, we need to get a reference to a particular view model. This can be done either by index, by name, or the default for a given artboard, and is done from the Rive file. The default option refers to the view model assigned to an artboard by the dropdown in the editor.
> [tab] New Runtime
>
> View models are not their own type; rather, they are a source when creating a view model instance from a `File`.
>
> You can define the source of a view model via the `ViewModelSource` type.
>
> ```swift theme={null}
> case artboardDefault(Artboard) // References the default view model for an Artboard
> case name(String) // References a view model from a file by name
> ```
>
> These sources are used in conjunction with getting a view model instance. See [View Model Instances](#view-model-instances) for more information.
> [tab] Legacy Runtime
>
> ```swift theme={null}
> let riveViewModel = RiveViewModel(...)
> let file = riveViewModel.riveModel!.riveFile
>
> // Data binding view model by name
> let viewModelByName = file.viewModelNamed("...")
>
> // Data binding view model by index
> for index in 0.. let viewModelByIndex = file.viewModel(at: index)
> }
>
> // Default data binding view model for an artboard
> let artboard = riveViewModel.riveModel!.artboard
> let viewModelForArtboard = file.viewModel(for: artboard)
> ```
# View Model Instances
Once we have a reference to a view model, it can be used to create an instance. When creating an instance, you have four options:
1. Create a blank instance - Fill the properties of the created instance with default values as follows:
| Type | Value |
| - | - |
| Number | 0 |
| String | Empty string |
| Boolean | False |
| Color | 0xFF000000 |
| Trigger | Untriggered |
| Enum | The first value |
| Image | No image |
| Font | No font |
| Artboard | No artboard |
| List | Empty list |
| Nested view model | Null |
2. Create the default instance - Use the instance labelled "Default" in the editor. Usually this is the one a designer intends as the primary one to be used at runtime.
3. Create by index - Using the order returned when iterating over all available instances. Useful when creating multiple instances by iteration.
4. Create by name - Use the editor's instance name. Useful when creating a specific instance.
> [!NOTE]
>
> In some samples, due to the wordiness of "view model instance", we use the abbreviation "VMI", as well as "VM" for "view model".
> [tab] New Runtime
>
> The following section assumes that you have read through the [Apple](/docs/runtimes/apple/apple) overview.
>
> ```swift theme={null}
> // From a file
> let file: File = ...
>
> // When using a view model by name:
> // A blank view model instance
> var blankInstance = try await file.createViewModelInstance(.blank(from: .name("ViewModel")))
> // The default instance for the view model
> var defaultInstance = try await file.createViewModelInstance(.viewModelDefault(from: .name("ViewModel")))
> // An instance by name from the view model
> var namedInstance = try await file.createViewModelInstance(.name("Instance", from: .name("ViewModel")))
>
> // Alternatively, using the default view model for an artboard
> let artboard: Artboard = ...
> // A blank view model instance
> blankInstance = try await file.createViewModelInstance(.blank(from: .artboardDefault(artboard)))
> // The default instance for the view model
> defaultInstance = try await file.createViewModelInstance(.viewModelDefault(from: .artboardDefault(artboard)))
> // An instance by name from the view model
> namedInstance = try await file.createViewModelInstance(.name("Instance", from: .artboardDefault(artboard)))
> ```
> [tab] Legacy Runtime
>
> ```swift theme={null}
> let riveViewModel = RiveViewModel(...)
> let viewModel = riveViewModel.riveModel!.riveFile.viewModelNamed("...")!
>
> // Create blank
> let blankInstance = viewModel.createInstance()
>
> // Create default
> let defaultInstance = viewModel.createDefaultInstance()
>
> // Create by index
> for index in 0.. let instanceByIndex = viewModel.createInstance(fromIndex: index)
> }
>
> // Create by name
> for name in viewModel.instanceNames {
> let instanceByName = viewModel.createInstance(fromName: name)
> }
> ```
### Binding
The created instance can then be assigned to a state machine or artboard. This establishes the bindings set up at edit time.
It is preferred to assign to a state machine, as this will automatically apply the instance to the artboard as well. Only assign to an artboard if you are not using a state machine, i.e. your file is static or uses linear animations.
> [!NOTE]
>
> The initial values of the instance are not applied to their bound elements until the state machine or artboard advances.
> [tab] New Runtime
>
> Create and retain the instance you want to read, observe, or modify, then bind it when creating the state machine. Run setup from a `@MainActor` async context.
>
> ```swift theme={null}
> let artboard = try await file.createArtboard()
> let viewModelInstance = try await file.createViewModelInstance(
> .viewModelDefault(from: .artboardDefault(artboard))
> )
> let stateMachine = try await artboard.createStateMachine(binding: viewModelInstance)
> let rive = try await Rive(file: file, artboard: artboard, stateMachine: stateMachine)
> ```
>
> To replace the main instance later, create a new instance and use the async throwing binding API:
>
> ```swift theme={null}
> let replacementInstance = try await file.createViewModelInstance(
> .viewModelDefault(from: .artboardDefault(artboard))
> )
> try await stateMachine.bindViewModelInstances(main: replacementInstance)
> ```
>
> After binding succeeds, retain `replacementInstance` for subsequent property access.
>
> The `Rive` initializer with an explicit artboard and state machine uses those components as configured, without rebinding. Create the artboard from the same file and the state machine from that artboard. Use compatible instances from the same file and worker.
>
> > [!WARNING]
> >
> > Bound instances cannot be retrieved from the state machine. The deprecated `Rive.viewModelInstance` property returns `nil` with the new initializers. Keep your own references for property access. See [migration guidance](/docs/runtimes/apple/migrating-from-legacy#updating-existing-concurrency-runtime-code).
> [tab] Legacy Runtime
>
> ```swift theme={null}
> let riveViewModel = RiveViewModel(...)
> let artboard = riveViewModel.riveModel!.artboard,
> let instance = riveViewModel.riveModel!.riveFile.defaultViewModel(for: artboard).createDefaultInstance()!
>
> // Apply the instance to the state machine (preferred)
> // Applying to a state machine will automatically bind to its artboard
> riveViewModel.riveModel!.stateMachine.bind(instance)
>
> // Alternatively, apply the instance to the artboard
> artboard.bind(viewModelInstance: instance)
> ```
### Auto-Binding
Alternatively, you may prefer to use auto-binding. This will automatically bind the default view model of the artboard using the default instance to both the state machine and the artboard. The default view model is the one selected on the artboard in the editor dropdown. The default instance is the one marked "Default" in the editor.
> [tab] New Runtime
>
> State machine creation binds authored main and global defaults when available. If you do not need programmatic access to those instances, use a convenience initializer:
>
> ```swift theme={null}
> let rive = try await Rive(file: file)
> ```
>
> To choose an artboard and use its default state machine:
>
> ```swift theme={null}
> let artboard = try await file.createArtboard("Artboard")
> let rive = try await Rive(file: file, artboard: artboard)
> ```
>
> Automatically created instances have no public getters. If you need to read or change their properties, create and retain instances explicitly as shown in [Binding](#binding).
> [tab] Legacy Runtime
>
> ```swift theme={null}
> let riveViewModel = RiveViewModel(...)
> riveViewModel.riveModel?.enableAutoBind { instance in
> // Store a reference to `instance` to later access properties
> // The instance may change as state machines and artboards change
> }
>
> // If you'd like to disable autoBind after enabling…
> riveViewModel.riveModel!.disableAutoBind()
> ```
## Global View Models
In the new Apple runtime, global view models provide shared data, such as a theme, to bindings authored to use that global. Create instances and bind them by their global view model names:
```swift theme={null}
let artboard = try await file.createArtboard()
let main = try await file.createViewModelInstance(
.viewModelDefault(from: .artboardDefault(artboard))
)
// This example requires a global view model named "Theme" in the file.
let theme = try await file.createViewModelInstance(
.viewModelDefault(from: .name("Theme"))
)
let stateMachine = try await artboard.createStateMachine(binding: main) {
("Theme", theme)
}
let rive = try await Rive(file: file, artboard: artboard, stateMachine: stateMachine)
```
To discover which global view models a file contains, use `try await file.getGlobalViewModelNames()`.
In this example, keep `main` and `theme` in your app's model if you need to access their properties. Global instances use the same property and observation APIs as the main instance. To share an instance across state machines from the same file, bind that same instance to each state machine.
You can replace only a global binding later:
```swift theme={null}
let darkTheme = try await file.createViewModelInstance(
.name("Dark", from: .name("Theme"))
)
try await stateMachine.bindViewModelInstances {
("Theme", darkTheme)
}
```
The globals builder supports `if`, `if let`, and `for` statements. For example, choose between instances named "Light" and "Dark" authored on the "Theme" view model:
```swift theme={null}
let lightTheme = try await file.createViewModelInstance(
.name("Light", from: .name("Theme"))
)
let darkTheme = try await file.createViewModelInstance(
.name("Dark", from: .name("Theme"))
)
// colorScheme is the current SwiftUI ColorScheme value from your app.
try await stateMachine.bindViewModelInstances {
if colorScheme == .dark {
("Theme", darkTheme)
} else {
("Theme", lightTheme)
}
}
```
The builder runs when you call the binding method. To switch themes when the color scheme changes, call it again with the updated value and your retained instances.
You can also pass `main:` to update main and global bindings in one call. Each call sets the supplied bindings; it does not replace the complete set of bindings. Omitting a global does not remove it or clear its instance—the existing binding stays in place. Slots without an existing or supplied instance receive authored defaults when available. Passing `nil` for `main` also preserves its existing binding rather than clearing it.
All supplied global names are checked before applying any supplied bindings. An unknown or non-global name throws `StateMachineError.invalidGlobalViewModelName`; duplicate names in one call throw `StateMachineError.duplicateGlobalViewModelInstance`. These rejected calls leave existing bindings intact. Metadata failures throw `StateMachineError.error`, and cancellation throws `StateMachineError.cancelled`. Name validation does not check instance type or worker compatibility.
# Properties
A property is a value that can be read, set, or observed on a view model instance. Properties can be of the following types:
| Type | Supported |
| - | - |
| Floating point numbers | ✅ |
| Booleans | ✅ |
| Triggers | ✅ |
| Strings | ✅ |
| Enumerations | ✅ |
| Colors | ✅ |
| Nested View Models | ✅ |
| Lists | ✅ |
| Images | ✅ |
| Artboards | ✅ |
For more information on version compatibility, see the [Feature Support](/docs/feature-support) page.
### Listing properties
Property descriptors can be inspected on a view model to discover at runtime which are available. These are not the mutable properties themselves though - once again those are on instances. These descriptors have a type and name.
> [tab] New Runtime
>
> ```swift theme={null}
> let file: File = ...
> let properties = try await file.getProperties(of: "ViewModel")
> for property in properties {
> print(property.type) // enum of string, number, boolean, etc
> print(property.name) // The name of the property within the view model
> print(property.metaData) // Additional metadata for the property, if available
> }
> ```
> [tab] Legacy Runtime
>
> ```swift theme={null}
> let riveViewModel = RiveViewModel(...)
> let viewModel = riveViewModel.riveModel!.file.viewModelNamed(...)!
> for property in viewModel.properties {
> print(property.type) // String, number, boolean, etc
> print(property.name) // The name of the property within the view model
> }
> ```
### Reading and writing properties
References to these properties can be retrieved by name or path.
Some properties are mutable and have getters, setters, and observer operations for their values. Getting or observing the value will retrieve the latest value set on that property's binding, as of the last state machine or artboard advance. Setting the value will update the value and all of its bound elements.
> [!NOTE]
>
> After setting a property's value, the changes will not apply to their bound elements until the state machine or artboard advances.
> [tab] New Runtime
>
> Property types are a very thin wrapper around the path and return type of a property.
>
> Property APIs are available on `ViewModelInstance`. Call them from a main-actor context. Reading a String, Number, Boolean, Color, or Enum property uses `try await`. Setting a property queues the change and returns immediately.
>
> | Property | Swift value | Supported operations |
> | - | - | - |
> | `StringProperty` | `String` | Read, write, `valueStream(of:)` |
> | `NumberProperty` | `Float` | Read, write, `valueStream(of:)` |
> | `BoolProperty` | `Bool` | Read, write, `valueStream(of:)` |
> | `ColorProperty` | `Color` | Read, write, `valueStream(of:)` |
> | `EnumProperty` | `String` | Read, write, `valueStream(of:)` |
> | `TriggerProperty` | No stored value | `fire(trigger:)`, `stream(of:)` |
> | `ImageProperty` | `Image?` | Write; `nil` clears |
> | `FontProperty` | `Font?` | Write; `nil` clears |
> | `BlobProperty` | `Blob?` | Write; `nil` clears |
> | `ArtboardProperty` | `Artboard?` | Write; `nil` clears |
> | `ViewModelInstanceProperty` | `ViewModelInstance` | Read and replace the nested instance |
> | `ListProperty` | List of View Model instances | Count, get, append, insert, remove, swap |
>
> Image, Font, Blob, and Artboard properties do not expose value getters or value streams. The View Model instance retains values assigned to these properties until they are replaced, cleared with `nil`, or the instance is released. Keep a strong reference to any decoded image, font, or blob, or created artboard, that you need to keep alive before assigning it. Images and fonts registered as global assets are also retained by the worker.
>
> Nested instances and list items expose their own property APIs.
>
> ```swift String theme={null}
> let file: File = ...
> let viewModelInstance = try await file.createViewModelInstance(...)
>
> // String
> let stringProperty = StringProperty(path: "path/to/string")
> let stringValue = try await viewModelInstance.value(of: stringProperty)
> viewModelInstance.setValue(of: stringProperty, to: "value")
> ```
>
> ```swift Number theme={null}
> let file: File = ...
> let viewModelInstance = try await file.createViewModelInstance(...)
>
> let numberProperty = NumberProperty(path: "path/to/number")
> let numberValue = try await viewModelInstance.value(of: numberProperty)
> viewModelInstance.setValue(of: numberProperty, to: 9001)
> ```
>
> ```swift Bool theme={null}
> let file: File = ...
> let viewModelInstance = try await file.createViewModelInstance(...)
>
> let boolProperty = BoolProperty(path: "path/to/bool")
> let boolValue = try await viewModelInstance.value(of: boolProperty)
> viewModelInstance.setValue(of: boolProperty, to: true)
> ```
>
> ```swift Color theme={null}
> let file: File = ...
> let viewModelInstance = try await file.createViewModelInstance(...)
>
> let colorProperty = ColorProperty(path: "path/to/color")
> let colorValue = try await viewModelInstance.value(of: colorProperty)
> viewModelInstance.setValue(of: colorProperty, to: Color(red: 255, green: 255, blue: 255, alpha: 255))
> ```
>
> ```swift Enum theme={null}
> let file: File = ...
> let viewModelInstance = try await file.createViewModelInstance(...)
>
> let enumProperty = EnumProperty(path: "path/to/enum")
> let enumValue = try await viewModelInstance.value(of: enumProperty)
> viewModelInstance.setValue(of: enumProperty, to: "value")
> ```
>
> ```swift Trigger theme={null}
> let file: File = ...
> let viewModelInstance = try await file.createViewModelInstance(...)
>
> let triggerProperty = TriggerProperty(path: "path/to/trigger")
> viewModelInstance.fire(trigger: triggerProperty)
> ```
> [tab] Legacy Runtime
>
> ```swift theme={null}
> let riveViewModel = RiveViewModel(...)
>
> var viewModelInstance: RiveDataBindingViewModel.Instance!
>
> // You can get the view model instance when enabling auto binding
> riveViewModel.riveModel?.enableAutoBind { instance in
> // Store a reference to instance
> viewModelInstance = instance
> }
>
> // Alternatively, you can create a view model instance manually
> viewModelInstance = riveViewModel.riveModel!.riveFile.viewModelNamed("...")!.createDefaultInstance()!
>
> // Strings
> let stringProperty = instance.stringProperty(fromPath: "...")!
> // Updating its value
> stringProperty.value = "Hello, Rive"
> // Get its value
> print(stringProperty.value)
>
> // You can also set and get values without storing a strong reference
> instance.stringProperty(fromPath: "...").value = "Hello again, Rive"
>
> // Numbers
> let numberProperty = instance.numberProperty(fromPath: "...")!
> // Updating its value
> numberProperty.value = 1337
> // Get its value
> print(numberProperty.value)
>
> // You can also set and get values without storing a strong reference
> instance.numberProperty(fromPath: "...").value = 1337
>
> // Booleans
> let booleanProperty = instance.booleanProperty(fromPath: "...")!
> // Updating its value
> booleanProperty.value = true
> // Get its value
> print(booleanProperty.value)
>
> // You can also set and get values without storing a strong reference
> instance.booleanProperty(fromPath: "...").value = true
>
> // Colors
> let colorProperty = instance.colorProperty(fromPath: "...")!
> // Updating its value, which is a UIColor/NSColor, so all static helpers apply.
> colorProperty.value = .red
> // Get its value
> print(colorProperty.value)
>
> // You can also set and get values without storing a strong reference
> instance.colorProperty(fromPath: "...").value = .red
>
> // Enums
> let enumProperty = instance.enumProperty(fromPath: "...")!
> // Updating its value
> enumProperty.value = "Foo"
> // Get its value
> print(enumProperty.value)
> // Print all possible values
> print(enumProperty.values)
>
> // You can also set and get values without storing a strong reference
> instance.enumProperty(fromPath: "...").value = "Foo"
>
> // Trigger
> let triggerProperty = instance.triggerProperty(fromPath: "...")!
> // Fire the trigger
> triggerProperty.trigger()
> ```
### Nested property paths
View models can have properties of type view model, allowing for arbitrary nesting. You can chain property calls on each instance starting from the root until you get to the property of interest. Alternatively, you can do this through a path parameter, which is similar to a URI in that it is a forward slash delimited list of property names ending in the name of the property of interest.
> [tab] New Runtime
>
> Use a `/`-separated path to access a nested property directly, or retrieve the nested instance with `ViewModelInstanceProperty`:
>
> ```swift theme={null}
> let title = StringProperty(path: "header/title")
> viewModelInstance.setValue(of: title, to: "Welcome")
>
> let headerProperty = ViewModelInstanceProperty(path: "header")
> let header = viewModelInstance.value(of: headerProperty)
> header.setValue(of: StringProperty(path: "title"), to: "Welcome")
>
> let replacement = try await file.createViewModelInstance(
> .viewModelDefault(from: .name("Header"))
> )
> viewModelInstance.setValue(of: headerProperty, to: replacement)
> ```
>
> Create replacements with a View Model compatible with the nested property, using the same worker.
> [tab] Legacy Runtime
>
> ```swift theme={null}
> let riveViewModel = RiveViewModel(...)
>
> var viewModelInstance: RiveDataBindingViewModel.Instance!
>
> // You can get the view model instance when enabling auto binding
> riveViewModel.riveModel?.enableAutoBind { instance in
> // Store a reference to instance
> viewModelInstance = instance
> }
>
> // Alternatively, you can create a view model instance manually
> viewModelInstance = riveViewModel.riveModel!.riveFile.viewModelNamed("...")!.createDefaultInstance()!
>
> let nestedNumberByChain = instance
> .viewModelInstanceProperty(fromPath: "Nested View Model")
> .viewModelInstanceProperty(fromPath: "Another Nested View Model")
> .numberProperty(fromPath: "Number")
>
> let nestedNumberByPath = instance.numberProperty(fromPath: "Nested View Model/Another Nested View Model/Number")
> ```
### Observability
You can observe changes over time to property values, either by using listeners or a platform equivalent method. Once observed, you will be notified when the property changes are applied by a state machine advance, whether that is a new value that has been explicitly set or if the value was updated as a result of a binding.
> [tab] New Runtime
>
> `RiveController` automatically redraws after changes to bound main and global instances, including nested and list child instances. You do not need to subscribe to the deprecated `dirtyStream()` API to request redraws. Use property streams to react to values in your app.
>
> String, Number, Boolean, Color, and Enum properties expose changes through Swift Concurrency's async throwing streams. Call `valueStream(of:)` on a `ViewModelInstance` object.
>
> ```swift theme={null}
> let file: File = ...
> let viewModelInstance = try await file.createViewModelInstance(...)
> let stringProperty = StringProperty(path: "path/to/string")
> let valueStream = viewModelInstance.valueStream(of: stringProperty)
> do {
> for try await value in valueStream {
> print(value)
> }
> } catch let error as ViewModelInstanceError {
> // The thrown error should always be a ViewModelInstanceError type
> print(error)
> } catch {
> print(error)
> }
> ```
>
> For triggers, you can listen to them by calling the `stream(of:)` method on a `ViewModelInstance` object. This returns a stream of `Void` values, which can be ignored.
>
> ```swift theme={null}
> let file: File = ...
> let viewModelInstance = try await file.createViewModelInstance(...)
> let triggerProperty = TriggerProperty(path: "path/to/trigger")
> let triggerStream = viewModelInstance.stream(of: triggerProperty)
> do {
> for try await _ in triggerStream {
> print("Trigger fired!")
> }
> } catch let error as ViewModelInstanceError {
> // The thrown error should always be a ViewModelInstanceError type
> print(error)
> } catch {
> print(error)
> }
> ```
> [tab] Legacy Runtime
>
> ```swift theme={null}
> let riveViewModel = RiveViewModel(...)
>
> var viewModelInstance: RiveDataBindingViewModel.Instance!
>
> // You can get the view model instance when enabling auto binding
> riveViewModel.riveModel?.enableAutoBind { instance in
> // Store a reference to instance
> viewModelInstance = instance
> }
>
> // Alternatively, you can create a view model instance manually
> viewModelInstance = riveViewModel.riveModel!.riveFile.viewModelNamed("...")!.createDefaultInstance()!
>
> // Get the String property
> let stringProperty = instance.stringProperty(fromPath: "...")!
>
> // Add a listener
> let listener = stringProperty.addListener { newValue in
> print(newValue)
> }
>
> // Remove a listener, where listener is the return value of addListener
> stringProperty.removeListener(listener)
>
> // Trigger properties can also be listened to for when they are triggered
> instance.triggerProperty(fromPath: "...")!.addListener {
> print("Triggered!")
> }
> ```
### Images
Image properties let you set and replace raster images at runtime, with each instance of the image managed independently. For example, you could build an avatar creator and dynamically update features — like swapping out a hat — by setting a view model's image property.
> [tab] New Runtime
>
> To set an image, you first need to decode an image from a `Worker`. This has to be the `Worker` that was used when initializing a `File`, from which you are setting the Image property of a view model instance.
>
> ```swift theme={null}
> let worker = try await Worker()
> let file = try await File(source: ..., worker: worker)
> let viewModelInstance = try await file.createViewModelInstance(...)
> let imageProperty = ImageProperty(path: "path/to/image")
> let imageData: Data = ...
> let image = try await worker.decodeImage(from: imageData)
> viewModelInstance.setValue(of: imageProperty, to: image)
> // Clear the image when needed.
> viewModelInstance.setValue(of: imageProperty, to: nil)
> ```
> [tab] Legacy Runtime
>
> ```swift theme={null}
> let riveViewModel = RiveViewModel(...)
>
> var viewModelInstance: RiveDataBindingViewModel.Instance!
>
> // You can get the view model instance when enabling auto binding
> riveViewModel.riveModel?.enableAutoBind { instance in
> // Store a reference to instance
> viewModelInstance = instance
> }
>
> // Alternatively, you can create a view model instance manually
> viewModelInstance = riveViewModel.riveModel!.riveFile.viewModelNamed("...")!.createDefaultInstance()!
>
> // Create a RiveRenderImage from data
> let data = Data(...)
> var image = RiveRenderImage(data: data)! // This can return nil if the data is not a valid image
>
> // Or, create a RiveRenderImage from a UIImage
> image = RiveRenderImage(image: UIImage(named: "my_image")!, format: .png)! // This can return nil if the image is not a valid jpg or png image
>
> let imageProperty = viewModelInstance.imageProperty(fromPath: "image")!
>
> // Once you have your data binding view model instance, you can set the Image property value
> imageProperty.setValue(image)
>
> // You can also pass nil to clear the image
> imageProperty.setValue(nil)
> ```
## Fonts
In the Apple concurrency API, decode a font with the same `Worker` used to load the instance's file, then assign it to a `FontProperty`.
```swift theme={null}
let fontData: Data = ...
let font = try await worker.decodeFont(from: fontData)
let fontProperty = FontProperty(path: "headingFont")
viewModelInstance.setValue(of: fontProperty, to: font)
// Clear the font when needed.
viewModelInstance.setValue(of: fontProperty, to: nil)
```
`decodeFont(from:)` also accepts `UIFont` on UIKit platforms and `NSFont` on macOS. See [Loading Assets](/docs/runtimes/apple/loading-assets) for decoding and global registration options.
## Blobs
A blob holds arbitrary binary data. Decode it with the same worker as the instance's file, then assign it to a Blob property:
```swift theme={null}
let data = Data([0x01, 0x02, 0x03])
let blob = try await worker.decodeBlob(from: data)
let blobProperty = BlobProperty(path: "payload")
viewModelInstance.setValue(of: blobProperty, to: blob)
// Clear the blob when needed.
viewModelInstance.setValue(of: blobProperty, to: nil)
```
### Lists
List properties let you manage a dynamic set of view model instances at runtime. For example, you can build a to-do app where users can add and remove tasks in a scrollable Layout.
See the [Editor section](/docs/editor/data-binding/lists) on creating data bound lists.
A single list property can include different view model types, with each view model tied to its own Component, making it easy to populate a list with a variety of Component instances.
With list properties, you can:
* Add a new view model instance (optionally at an index)
* Remove an existing view model instance (optionally by index)
* Swap two view model instances by index
* Get the size of a list
For more information on list properties, see the [Data Binding List Property](/docs/editor/data-binding/lists#view-model-list-property) editor documentation.
> [tab] New Runtime
>
> ```swift theme={null}
> let file: File = ...
> let viewModelInstance = try await file.createViewModelInstance(...)
> let listProperty = ListProperty(path: "path/to/list")
>
> let size = try await viewModelInstance.size(of: listProperty)
>
> // Result: [newInstance]
> let newInstance = try await file.createViewModelInstance(...)
> viewModelInstance.appendInstance(newInstance, to: listProperty)
>
> // Result: [insertedInstance, newInstance]
> let insertedInstance = try await file.createViewModelInstance(...)
> viewModelInstance.insertInstance(insertedInstance, to: listProperty, at: 0)
>
> // Result: [newInstance, insertedInstance]
> viewModelInstance.swapInstance(atIndex: 0, withIndex: 1, in: listProperty)
>
> // Result: [newInstance]
> viewModelInstance.removeInstance(at: 1, from: listProperty)
>
> // Result: newInstance
> let _ = viewModelInstance.value(of: listProperty, at: 0)
>
> // Result: []
> viewModelInstance.removeInstance(newInstance, from: listProperty)
>
> // Result: 0
> let finalSize = try await viewModelInstance.size(of: listProperty)
> ```
> [tab] Legacy Runtime
>
> ```swift theme={null}
> let listProperty = viewModelInstance.listProperty(fromPath: "list")!
>
> // Create a new view model instance and add it to the end of the list
> let firstInstance = viewModel.createInstanceByName("First Instance")!
> listProperty.add(firstInstance)
>
> // Create a new view model instance and add it to the beginning of the list
> let secondInstance = myViewModel.createInstanceByName("Second Instance")!
> listProperty.add(secondInstance, atIndex: 0)
>
> // Swap the first and second instances
> listProperty.swapInstance(atIndex: 0, withInstanceAtIndex: 1)
>
> // Remove both instances
> listProperty.removeInstance(secondInstance)
> listProperty.removeInstance(atIndex: 0)
>
> // Get and print the size of the list
> print(listProperty.size) // Prints 0
> ```
### Artboards
Artboard properties allows you to swap out entire components at runtime. This is useful for creating modular components that can be reused across different designs or applications, for example:
* Creating a skinning system that supports a large number of variations, such as a character creator where you can swap out different body parts, clothing, and accessories.
* Creating a complex scene that is a composition of various artboards loaded from various different Rive files (drawn to a single canvas/texture/widget).
* Reducing the size (complexity) of a single Rive file by breaking it up into smaller components that can be loaded on demand and swapped in and out as needed.
> [tab] New Runtime
>
> ```swift theme={null}
> let file: File = ...
> let viewModelInstance = try await file.createViewModelInstance(...)
> let artboardProperty = ArtboardProperty(path: "path/to/artboard")
> let artboard = try await file.createArtboard(...)
> viewModelInstance.setValue(of: artboardProperty, to: artboard)
> // Clear the artboard when needed.
> viewModelInstance.setValue(of: artboardProperty, to: nil)
> ```
> [tab] Legacy Runtime
>
> Use the `artboardProperty` method on a `RiveDataBindingViewModel.Instance` object to get the Artboard property.
>
> Then use the `setValue` method on the Artboard property object to set the new artboard value.
>
> `setValue` accepts a `RiveBindableArtboard` object, which is a wrapper for an artboard that can be used to set the Artboard property value.
>
> You can get a `RiveBindableArtboard` object by using the `bindableArtboard` methods on a `RiveFile` object.
>
> ```swift theme={null}
> let artboardProperty = instance.artboardProperty(fromPath: "Artboard")!
>
> let components = RiveFile(...)
> let bindableArtboard = components.bindableArtboard(at: 0)!
> let bindableArtboard2 = components.bindableArtboard(withName: "...")!
>
> artboardProperty.setValue(bindableArtboard)
> ```
### Enums
Enums properties come in two flavors: system and user-defined. In practice, you will not need to worry about the distinction, but just be aware that system enums are available in any Rive file that binds to an editor-defined enum set, representing options from the editor's dropdowns, where user-defined enums are those defined by a designer in the editor.
Enums are string typed. The Rive file contains a list of enums. Each enum in turn has a name and a list of strings.
## Examples
See the [Data Binding view](https://github.com/rive-app/rive-ios/blob/main/Example-iOS/Source/Examples/SwiftUI/DataBindingView.swift) in the Example app for a demo.
# Deferred File Loading
Source: https://rive.app/docs/runtimes/apple/deferred-file-loading
Decode the contents of a Rive file the first time they're used instead of while it loads.
By default, a Rive file decodes everything in the `.riv` file while it loads, including every artboard, animation, and view model instance. With deferred decoding, the runtime decodes most of these the first time you use them, so a file can be ready sooner when you only use part of it.
## When to defer decoding
Deferred decoding is most useful for large files where you show only some of the artboards at a time. It moves decoding work from load time to first use:
* Loading can finish sooner, because unused contents aren't decoded.
* The first use of each deferred artboard, animation, or view model instance can take longer, because it decodes then.
* The runtime keeps a copy of the bytes for each deferred part in memory until that part decodes.
Tip
**Example - Level select**
Your file has a level select screen with 30 levels, each on its own artboard. A player opens one level at a time. With deferred decoding, the file loads without decoding all 30 artboards, and each level's artboard decodes when the player opens it.
For small files, or files where you use every artboard right away, keep the default eager decoding.
## What decodes on first use
With deferred decoding on, the runtime still reads all of the file's bytes while loading. It defers decoding of these parts:
| Part | Decodes when |
| - | - |
| Artboards | You first create an instance of the artboard. The default artboard still decodes while the file loads. |
| Animations | An artboard or State Machine first uses the animation. |
| View model instances | You first create an instance from the view model. Instances inside an artboard decode with that artboard. |
Some parts can't wait and decode while loading as usual.
> [!TIP]
>
> To avoid a delay the first time you show an artboard, create it ahead of time, such as while a previous screen is visible.
## Handling errors
With eager decoding, a malformed file fails to load. With deferred decoding, the runtime doesn't check deferred parts while loading, so loading can succeed and errors appear on first use instead:
* Creating a malformed artboard fails.
* An artboard that nests a malformed artboard loads with the nested artboard empty.
* A malformed view model instance keeps only the values read before the error.
## Example usage
Deferred decoding is available in the New Runtime from v6.31.0.
### Enabling deferred decoding
Pass a `File.Configuration` with `deferDecoding` set to `true` when you create the file. The configuration applies for the life of the file.
```swift highlight={5} theme={null}
let worker = try await Worker()
let file = try await File(
source: .local("my_file", Bundle.main),
worker: worker,
configuration: .init(deferDecoding: true)
)
```
The `configuration` argument defaults to `File.Configuration()`, which decodes eagerly.
Eager and deferred files can share a `Worker`. You choose the decoding mode per file. Deferred parts decode on the `Worker` that owns the file.
### Handling artboard errors
Creating a malformed artboard with `createArtboard(_:)` throws `FileError.invalidArtboard`.
```swift theme={null}
do {
let artboard = try await file.createArtboard("Level 12")
// Use the artboard.
} catch FileError.invalidArtboard(let message) {
// The artboard doesn't exist, or failed to decode.
print(message)
}
```
# FAQ
Source: https://rive.app/docs/runtimes/apple/faq
## How do I enable support for ProMotion displays?
Support for ProMotion on iOS requires two things:
1. Using an API in the Apple runtime to set the desired FPS (range)
2. Adding an additional entry into your app's`Info.plist` file
### Example usage
```swift theme={null}
let preferredFPS = UIScreen.main.maximumFramesPerSecond
// or
let preferredFPSRange = CAFrameRateRange(minimum: 60, maximum: Float(preferredFPS))
let viewModel = {
let viewModel = RiveViewModel(fileName: "...")
viewModel.setPreferredFramesPerSecond(preferredFramesPerSecond: preferredFPS)
// or
viewModel.setPreferredFrameRateRange(preferredFPSRange)
return viewModel
}()
```
Additionally, add the following to your app's `Info.plist` file:
`CADisableMinimumFrameDurationOnPhone `
You can view more information about preferred FPS [here](https://developer.apple.com/documentation/quartzcore/cadisplaylink/1648421-preferredframespersecond), and about preferred FPS range [here](https://developer.apple.com/documentation/quartzcore/cadisplaylink/3875343-preferredframeraterange).
### Why is resource usage different compared to other libraries?
See our [Resource Usage](/docs/runtimes/apple/resource-usage) documentation for more details.
# Focus
Source: https://rive.app/docs/runtimes/apple/focus
Navigate Rive graphics with a keyboard or Apple TV remote in the Apple runtime.
With the Swift Concurrency API, your Rive view joins native focus navigation automatically when the graphic has [focus nodes](/docs/editor/accessibility/focus#making-an-element-focusable). The platform moves focus between views. Rive moves focus between elements in the graphic.
## Native focus
Rive discovers focus nodes asynchronously after loading. The graphic can appear before the view can receive focus.
> [!NOTE]
>
> Native focus varies by platform. See Apple's guidance for [iPadOS 15 and later, tvOS, and visionOS](https://developer.apple.com/design/human-interface-guidelines/focus-and-selection/) and [Mac Catalyst](https://developer.apple.com/documentation/uikit/navigating-an-app-s-user-interface-using-a-keyboard). iPhone offers [Full Keyboard Access](https://developer.apple.com/videos/play/wwdc2021/10120/) as a separate accessibility feature.
> [tab] SwiftUI
>
> `RiveUIViewRepresentable` and `AsyncRiveUIViewRepresentable` become focusable automatically when the graphic is ready. Add either view directly to your SwiftUI hierarchy.
> [tab] UIKit
>
> To make `RiveUIView` the preferred target for initial focus, return it from the hosting view controller's `preferredFocusEnvironments`.
>
> ```swift theme={null}
> // In the view controller that hosts riveView.
> override var preferredFocusEnvironments: [any UIFocusEnvironment] {
> [riveView]
> }
> ```
>
> UIKit considers this preference when it updates focus. If a native control already has focus, loading the graphic leaves focus on that control. See Apple's [UIFocusEnvironment documentation](https://developer.apple.com/documentation/uikit/uifocusenvironment).
> [tab] AppKit
>
> The Rive view joins the window's key-view loop. Use `NSWindow`'s `selectNextKeyView(_:)` or `selectPreviousKeyView(_:)` to move through the loop from code. See [AppKit's key-view APIs](https://developer.apple.com/documentation/appkit/nswindow#Managing-the-Key-View-Loop).
## Requesting keyboard input
Keys go to the element that has focus, and the first element gets focus when the user navigates into the graphic, usually by pressing **Tab**. To send hardware-keyboard input to a graphic without that first **Tab**, such as WASD controls that work as soon as the graphic appears, make the view the keyboard responder.
A request succeeds when the graphic is loaded, playing, in the key window, and has focus nodes. Rive then tries to focus the first element in the [focus order](/docs/editor/accessibility/focus#focus-order), unless an element already has focus.
> [!NOTE]
>
> Requesting keyboard input doesn't enable text input or show the software keyboard.
> [tab] SwiftUI
>
> Call `keyboardFocused(_:onResult:)` on `RiveUIViewRepresentable` or `AsyncRiveUIViewRepresentable`, before any SwiftUI modifiers. The view waits until the graphic is ready before it makes the request.
>
> ```swift highlight={5} theme={null}
> @State private var wantsKeyboardInput = true
>
> var body: some View {
> RiveUIViewRepresentable(rive: rive)
> .keyboardFocused(wantsKeyboardInput)
> }
> ```
>
> Each change to `true` makes one request, and a change to `false` gives up keyboard input. To request again, such as after you replace the view's content, set the value to `false` and then back to `true` in a later update.
>
> To learn whether an attempt succeeded, pass `onResult`. Rive calls it after each attempt with the action, `.become` or `.resign`, and whether it succeeded.
>
> A change to `true` while the view is paused makes no request. Pausing or removing the view, or a loading failure, cancels a pending request. Rive doesn't call `onResult` in these cases.
>
> Avoid combining `keyboardFocused(_:onResult:)` with SwiftUI's `focused(_:)` on the same view.
> [tab] UIKit
>
> Call `becomeKeyboardResponder()` on `RiveUIView`. It returns whether the request succeeded.
>
> ```swift theme={null}
> let succeeded = riveView.becomeKeyboardResponder()
> ```
>
> The request runs immediately and isn't queued. It returns `false` until the graphic is ready, so a call made as soon as the view appears usually fails. Call it again later, such as when the user first interacts with the graphic.
>
> To give up keyboard input, call `resignKeyboardResponder()`.
> [tab] AppKit
>
> Call `becomeKeyboardResponder()` on `RiveUIView`. It returns whether the request succeeded.
>
> ```swift theme={null}
> let succeeded = riveView.becomeKeyboardResponder()
> ```
>
> The request runs immediately and isn't queued. It returns `false` until the graphic is ready, so a call made as soon as the view appears usually fails. Call it again later, such as when the user first interacts with the graphic.
>
> To give up keyboard input, call `resignKeyboardResponder()`.
On iOS, iPadOS, visionOS, and Mac Catalyst, **Tab** and the arrow keys don't [move between elements](#moving-between-elements) until the view also has native focus. After you replace a view's content, request keyboard input again.
## Moving between elements
* **Tab** and **Shift+Tab** follow the focus order set in the editor.
* **Arrow keys** move focus in the direction you press.
* On **tvOS**, the Siri Remote also moves focus. Rive treats the remote's Select button as **Enter**. See [Apple TV focus interactions](https://developer.apple.com/documentation/uikit/about-focus-interactions-for-apple-tv).
Rive waits for the State Machine to handle each key before deciding whether to pass it back to the platform. [Keyboard listeners](/docs/editor/state-machine/listeners#keyboard) get the key before focus navigation does. For example, if Rive leaves **Tab** unhandled at the last element, the platform can move focus to the next native control.
Full Keyboard Access and gamepad navigation outside tvOS fall outside the Apple runtime's focus support. Use [Semantics](/docs/runtimes/apple/semantics) for VoiceOver.
# Fonts
Source: https://rive.app/docs/runtimes/apple/fonts
Loading and replacing fonts dynamically at runtime.
## Swapping font assets at runtime
Fonts can be loaded dynamically at runtime. This allows you to localize your Rive content without increasing the file size of the exported .riv file.
Swapping a font asset replaces all instances of the font.
For more information, see [Loading Assets](/docs/runtimes/apple/loading-assets).
## Fallback fonts
When rendering text, not all glyphs (characters) may be available in the active font. This commonly occurs when:
* Using custom fonts that don’t support all languages or Unicode ranges
* The embedded font is a subset of the font
* User-generated or dynamic text contains unexpected characters
A fallback font is used automatically when the primary font cannot render a specific glyph. These are typically system fonts, which generally provide broad Unicode coverage.
> [!NOTE]
>
> On iOS, font sizes specified for fallback fonts are ignored. Instead, the platform selects system fonts that best match the styling and animation of the text run at runtime.
As of v6.1, on iOS and macOS, various options for fallbacks can be used. The Apple runtime provides helpers for selecting system fonts based on requested styling. Additionally, UIFonts / NSFonts can be used directly.
> [!NOTE]
>
> A default system font of regular weight and width will be used if no fallbacks have been registered.
```swift theme={null}
// Early in your app lifecycle, call something similar to the following:
RiveFont.fallbackFonts = [
RiveFallbackFontDescriptor(), // Use a default system font
RiveFallbackFontDescriptor(design: .default, weight: .bold, width: .expanded), // Use a bold, expanded system font
UIFont(name: "...", size: 20)!
]
// Alternatively, you can supply different fonts based on style at runtime
```
As of v6.4, on iOS and macOS, you can utilize a more dynamic callback-based API for returning various fonts depending on the style of any missing characters, as styled in a text run.
```swift theme={null}
// As with the similar fallbackFonts API, you utilize Rive helper types
// or native UIFont/NSFont types
RiveFont.fallbackFontsCallback = { style in
switch style.weight {
case .thin: return [
RiveFallbackFontDescriptor(weight: .thin),
UIFont.systemFont(ofSize: 20, weight: .thin)
]
case .bold: return [
RiveFallbackFontDescriptor(weight: .bold),
UIFont.systemFont(ofSize: 20, weight: .bold)
]
default: return [
RiveFallbackFontDescriptor(),
UIFont.systemFont(ofSize: 20)
]
}
}
// Alternatively, you can use the raw weight to return various fonts as well
RiveFont.fallbackFontsCallback = { style in
switch style.rawWeight {
case 100: return [
RiveFallbackFontDescriptor(weight: .thin),
UIFont.systemFont(ofSize: 20, weight: .thin)
]
case 700: return [
RiveFallbackFontDescriptor(weight: .bold),
UIFont.systemFont(ofSize: 20, weight: .bold)
]
default: return [
RiveFallbackFontDescriptor(),
UIFont.systemFont(ofSize: 20)
]
}
}
```
# GPU Canvas
Source: https://rive.app/docs/runtimes/apple/gpu-canvas
Enable GPU Canvas when creating a Worker in the Apple runtime.
GPU Canvas enables 3D content in the Apple runtime. It is available through the Swift Concurrency API and is configured when creating a `Worker`. The setting applies to every `File` loaded by that worker and every `Rive` object created from those files.
> [!NOTE]
>
> GPU Canvas is required to render 3D content.
## Enabling GPU Canvas
Pass a configuration with `enableGPUCanvas` set to `true` when creating a worker:
```swift theme={null}
let worker = try await Worker(
configuration: .init(enableGPUCanvas: true)
)
```
The worker's GPU Canvas setting is fixed for its lifetime. Enable it before loading any files that require GPU Canvas or 3D support.
Every `File` created with the worker uses the same setting:
```swift theme={null}
let worker = try await Worker(
configuration: .init(enableGPUCanvas: true)
)
let file = try await File(
source: .local("my_file", Bundle.main),
worker: worker
)
let rive = try await Rive(file: file)
```
No additional configuration is required when creating a `RiveUIView`, `RiveUIViewRepresentable`, or `AsyncRiveUIViewRepresentable`. Each view inherits the GPU Canvas setting from the worker associated with its `Rive` object.
## Default behavior
GPU Canvas is disabled by default. Continue to create a worker without a configuration when your content does not require it:
```swift theme={null}
let worker = try await Worker()
```
## Sharing a GPU Canvas worker
Share a GPU Canvas worker when multiple files or views can use the same worker. An example implementation is shown below.
> [!NOTE]
>
> `AsyncShared` and the `Worker` extensions below are application-level helpers. They are not included with `RiveRuntime`.
```swift AsyncShared.swift theme={null}
/// Lazily creates and caches a value. Failed initialization can be retried.
@MainActor
final class AsyncShared {
private let makeValue: @MainActor () async throws -> Value
private var cachedValue: Value?
private var loadingTask: Task?
init(_ makeValue: @escaping @MainActor () async throws -> Value) {
self.makeValue = makeValue
}
func value() async throws -> Value {
if let cachedValue {
return cachedValue
}
let task = loadingTask ?? Task {
defer { loadingTask = nil }
let value = try await makeValue()
cachedValue = value
return value
}
loadingTask = task
return try await task.value
}
}
```
```swift AsyncShared+Worker.swift theme={null}
import RiveRuntime
extension AsyncShared where Value == Worker {
convenience init(configuration: Worker.Configuration = .init()) {
self.init {
try await Worker(configuration: configuration)
}
}
}
extension Worker {
@MainActor
private static let sharedWorker = AsyncShared()
@MainActor
private static let sharedGPUCanvasWorker = AsyncShared(
configuration: .init(enableGPUCanvas: true)
)
@MainActor
static func shared() async throws -> Worker {
try await sharedWorker.value()
}
@MainActor
static func sharedGPUCanvas() async throws -> Worker {
try await sharedGPUCanvasWorker.value()
}
}
```
Use `Worker.sharedGPUCanvas()` when loading files that require GPU Canvas:
```swift theme={null}
let worker = try await Worker.sharedGPUCanvas()
let file = try await File(
source: .local("my_file", Bundle.main),
worker: worker
)
let rive = try await Rive(file: file)
```
For a complete setup example, see the [Apple quick start](/docs/runtimes/apple/apple#getting-started).
# Layout
Source: https://rive.app/docs/runtimes/apple/layouts
Control how graphics are laid out within the canvas.
## The Fit Mode
A Rive graphic authored in the editor will not necessarily match the size of the container it is rendered into at runtime. We need to determine the behavior for this scenario, as no one size fits all.
The solution is choosing the fit mode. This is specified on the container and controls how Rive is scaled.
* `Layout`: Use the Rive layout engine to apply responsive layout to the artboard, matching the container dimensions. For this to work, the artboard must be designed with layouts in mind. See [Responsive Layouts](#responsive-layouts) for more information on how to use this option.
* `Contain`: **(Default)** Preserve aspect ratio and scale the artboard so that its larger dimension matches the corresponding dimension of the container.
If aspect ratios are not identical, this will leave space on the shorter dimension's axis.
* `ScaleDown`: Preserve aspect ratio and behave like `Contain` when the artboard is larger than the container. Otherwise, use the artboard's original dimensions.
* `Cover`: Preserve aspect ratio and scale the artboard so that its smaller dimension matches the corresponding dimension of the container.
If aspect ratios are not identical, this will clip the artboard on the larger dimension's axis.
* `FitWidth`: Preserve aspect ratio and scale the artboard width to match the container's width.
If the aspect ratios between the artboard and container do not match, this will result in either vertical clipping or space in the vertical axis.
* `FitHeight`: Preserve aspect ratio and scale the artboard height to match the container's height.
If the aspect ratios between the artboard and container do not match, this will result in either horizontal clipping or space in the horizontal axis.
* `Fill`: Do not preserve aspect ratio and stretch to the container's dimensions.
* `None`: Do not scale. Use the artboard's original dimensions.
For either dimension, if the artboard's dimension is larger, it will be clipped. If it is smaller, it will leave space.
### Alignment
In all options other than `Layout` and `Fill`, there is the possibility that the Rive graphic is clipped or leaves space within its container. Alignment determines how content aligns within the container. The following options are available.
* `TopLeft`
* `TopCenter`
* `TopRight`
* `CenterLeft`
* `Center` **(Default)**
* `CenterRight`
* `BottomLeft`
* `BottomCenter`
* `BottomRight`
### Applying the Fit Mode
> [tab] New Runtime
>
> You can set the fit and layout options on a `Rive` object. The `.fit` can be updated at runtime without creating a new `Rive` object.
>
> For all possible options, see [Fit.swift](https://github.com/rive-app/rive-ios/blob/main/Source/Concurrency/View/Fit.swift)
>
> ```swift theme={null}
> // Set a fit and alignment for an artboard that does not use layouts
> let worker = try await Worker()
> let file = try await File(source: ..., worker: worker)
> var rive = try await Rive(file: file, fit: .contain(alignment: .center))
> // Update the fit and alignment at runtime
> rive.fit = .fitWidth(alignment: .topCenter)
> ```
> [tab] Legacy Runtime
>
> The runtime provides the following enums to set on layout parameters:
>
> * **Fit**
> * `.fill`
> * `.contain`
> * `.cover`
> * `.fitWidth`
> * `.fitHeight`
> * `.scaleDown`
> * `.noFit`
> * **Alignment**
> * `.topLeft`
> * `.topCenter`
> * `.topRight`
> * `.centerLeft`
> * `.center`
> * `.centerRight`
> * `.bottomLeft`
> * `.bottomCenter`
> * `.bottomRight`
>
> ### SwiftUI
>
> The following example shows how to set layout parameters and switch them at runtime:
>
> ```swift theme={null}
> struct SwiftLayout: View {
> @State private var fit: RiveFit = .contain
> @State private var alignment: RiveAlignment = .center
>
> var body: some View {
> VStack {
> RiveViewModel(fileName: "fancy_rive_file", fit: fit, alignment: alignment).view()
> }
> HStack {
> Text("Some Fit Examples")
> }
> HStack {
> Button("Fill") { fit = .fill }
> Button("Contain") { fit = .contain }
> Button("Cover") { fit = .cover }
> }
> HStack {
> Text("Some Alignment Examples")
> }
> HStack {
> Button("Top Left") { alignment = .topLeft }
> Button("Top Center") { alignment = .topCenter }
> Button("Top Right") { alignment = .topRight }
> }
> }
> }
> ```
>
> ### UIKit
>
> The following example shows how to set layout parameters and switch them at runtime:
>
> ```swift theme={null}
> class LayoutViewController: UIViewController {
> @IBOutlet weak var riveView: RiveView!
> var viewModel = RiveViewModel(fileName: "fancy_rive_file")
>
> override func viewDidLoad() {
> viewModel.setView(riveView)
> }
>
> @IBAction func fitButtonTriggered(_ sender: UIButton) {
> setFit(name: sender.currentTitle!)
> }
>
> @IBAction func alignmentButtonTriggered(_ sender: UIButton) {
> setAlignment(name: sender.currentTitle!)
> }
>
> func setFit(name: String) {
> var fit: RiveFit = .contain
> switch name {
> case "Fill": fit = .fill
> case "Contain": fit = .contain
> case "Cover": fit = .cover
> case "Fit Width": fit = .fitWidth
> case "Fit Height": fit = .fitHeight
> case "Scale Down": fit = .scaleDown
> case "None": fit = .noFit
> default: fit = .contain
> }
> viewModel.fit = fit
> }
>
> func setAlignment(name: String) {
> var alignment: RiveAlignment = .center
> switch name {
> case "Top Left": alignment = .topLeft
> case "Top Center": alignment = .topCenter
> case "Top Right": alignment = .topRight
> case "Center Left": alignment = .centerLeft
> case "Center": alignment = .center
> case "Center Right": alignment = .centerRight
> case "Bottom Left": alignment = .bottomLeft
> case "Bottom Center": alignment = .bottomCenter
> case "Bottom Right": alignment = .bottomRight
> default: alignment = .center
> }
> viewModel.alignment = alignment
> }
> }
> ```
## Responsive Layouts
Rive’s layout feature lets you design resizable artboards with built-in responsive behavior, configured from the editor. Ensure the fit mode is set to **Layout** at runtime and the artboard will resize to fill its container according to the constraints defined in the editor.
Optionally you may provide a **layout scale factor** to multiply the scale of the content. This allows fine tuning the visual size within your container. This property only applies when setting the **Fit** mode to **Layout**.
For more Editor information and how to configure your graphic, see [Layouts Overview](/docs/editor/layouts/layouts-overview).
> [tab] New Runtime
>
> When creating a new `Rive` object, you can set the fit to layout, with two options for the scale factor: automatic or explicit.
>
> ```swift theme={null}
> let worker = try await Worker()
> let file = try await File(source: ..., worker: worker)
> // Create a new Rive object with a layout fit that automatically determines the scale factor based on the screen the view is being displayed on
> var rive = try await Rive(file: file, fit: .layout(scaleFactor: .automatic))
> // Or, use an explicit scale factor
> rive.fit = .layout(scaleFactor: .explicit(2.0))
> ```
> [tab] Legacy Runtime
>
> **Examples**
>
> * [SwiftUI](https://github.com/rive-app/rive-ios/blob/main/Example-iOS/Source/Examples/SwiftUI/SwiftLayout.swift)
>
> **Steps**
>
> 1. Set `fit` on an instance of `RiveViewModel` to `layout`
>
> 2. Optionally set `layoutScaleFactor` on `RiveViewModel` for manual control of an artboard's scale factor.
>
> > [!NOTE]
> >
> > To enable automatically determining the scale factor, set `.layoutScaleFactor` to `RiveViewModel.layoutScaleFactorAutomatic`. This is the default value; it is equivalent to `-1`. When set, Rive will listen for window and screen changes for the view model's view, and automatically apply the correct scale factor for the current view hierarchy.
>
> ```swift theme={null}
> let viewModel = RiveViewModel(fileName: "...")
> viewModel.fit = .layout
> viewModel.layoutScaleFactor = RiveViewModel.layoutScaleFactorAutomatic // Allow Rive to determine the scale factor
> viewModel.layoutScaleFactor = 2.0 // Or, explicitly set the scale factor
> ```
# Loading Assets
Source: https://rive.app/docs/runtimes/apple/loading-assets
Loading and replacing assets dynamically at runtime
> [!NOTE]
>
> If you want to dynamically replace images, use [image data binding](data-binding#images).
Some Rive files may contain assets that can be embedded within the actual file binary, such as font, image, or audio files. The Rive runtimes may then load these assets when the Rive file is loaded. While this makes for easy usage of the Rive files/runtimes, there may be opportunities to load these assets in or even replace them at runtime instead of embedding them in the file binary.
There are several benefits to this approach:
* Keep the `.riv` files tiny without potential bloat of larger assets
* Dynamically load an asset for any reason, such as loading an image with a smaller resolution if the `.riv` is running on a mobile device vs. an image of a larger resolution for desktop devices
* Preload assets to have available immediately when displaying your `.riv`
* Use assets already bundled with your application, such as font files
* Sharing the same asset between multiple `.riv`s
## Methods for loading assets
There are currently three different ways to load assets for your Rive files.
In the Rive editor select the desired asset from the **Assets** tab, and in the inspector choose the desired export option:

### Embedded assets
In the Rive editor, static assets can be included in the `.riv` file, by choosing the *"Embedded"* export type. As stated in the beginning of this page, when the Rive file gets loaded, the runtime will implicitly attempt to load in the assets embedded in the `.riv` as well, and you don't need to concern yourself with loading any assets manually.
**Caveat:** Embedded assets may bulk up the file size, especially when it comes to fonts when using Rive Text ([Text Overview](/docs/editor/text/text-overview)).
> [!NOTE]
>
> **Embedded is the default option.**
### Image CDNs
Some image CDNs allow for on-the-fly image transformations, including resizing, cropping, and automatic format conversion based on the browser's and device's capabilities. These CDNs can host your Rive image assets. Note that for these CDNs, you may need to specify the accepted formats, for example, as part of the HTTP header request:
```html theme={null}
... headers: { Accept: 'image/png,image/webp,image/jpeg,*/*', } ...
```
Please see your CDN provider's documentation for additional information.
> [!WARNING]
>
> Rive supports the following image formats: **jpeg**, **png**, and **webp**
### Referenced assets
In the Rive editor, you can mark an imported asset as a *"Referenced"* export type, which means that when you export the `.riv` file, the asset will not be embedded in the file binary, and the responsibility of loading the asset will be handled by your application at runtime.
This option enables you to dynamically load in assets via a handler API when the runtime begins loading in the `.riv` file. This option is preferable if you have a need to dynamically load in a specific asset based on any kind of app/game logic, and especially if you want to keep the .riv file size small.
All referenced assets, including the `.riv`, will be bundled as a zip file when you export your animation.
**Caveat:** You will need to provide an asset handler API when loading in Rive which should do the work of loading in an asset yourself. See [Handling Assets](#handling-assets).
> [!NOTE]
>
> SVG assets can't currently be loaded at runtime as referenced assets.
>
> This is because SVGs are converted to Rive vector objects, which are always embedded into the .riv.
## Handling assets
> [tab] New Runtime
>
> This section assumes that you have read through the [Apple](/docs/runtimes/apple/apple) overview.
>
> ### Asset API coverage
>
> Decode assets with the same `Worker` that owns the files or View Model instances using them.
>
> | Asset | Decode input | Global registration | Data Binding |
> | - | - | - | - |
> | Image | `decodeImage(from: Data)` | `addGlobalImageAsset(_:name:)` | `ImageProperty` |
> | Font | `decodeFont(from: Data)`, `UIFont`, or `NSFont` | `addGlobalFontAsset(_:name:)` | `FontProperty` |
> | Audio | `decodeAudio(from: Data)` | `addGlobalAudioAsset(_:name:)` | No Audio property API |
> | Blob | `decodeBlob(from: Data)` | Not supported | `BlobProperty` |
>
> Global registration replaces matching file assets by `uniqueName` across a worker. [Data Binding](/docs/runtimes/apple/data-binding) assigns an asset to a specific View Model property; it does not require global registration.
>
> > [!NOTE]
> >
> > Blobs support decoding and assignment through `BlobProperty`, but not global registration or removal. The examples below skip `.blob` assets; use Data Binding to assign a decoded blob.
>
> ### Discovering and Loading File Assets
>
> Use `File.getAssets()` to discover a file's assets, then decode and register replacements on its `Worker`. This replaces the legacy `customLoader` callback for out-of-band assets.
>
> A global asset applies to matching assets in that file and other files loaded by the same worker, including files loaded later. Register it using `asset.uniqueName`. You can register assets after creating the file, and register a new asset under the same unique name to replace it.
>
> Each `File.Asset` provides the following metadata:
>
> | Property | Description |
> | - | - |
> | `name` | The authored asset name stored in the file. |
> | `uniqueName` | The exact name to pass to the worker's global asset APIs. |
> | `assetID` | The asset identifier stored in the file. |
> | `type` | `.image`, `.font`, `.audio`, `.blob`, or `.unknown(UInt16)`. |
> | `fileExtension` | The file extension without a leading period. |
> | `cdn` | Optional hosted asset metadata with `baseURL` and `uuid`. |
>
> `getAssets()` includes embedded and referenced assets. Use the metadata to choose which assets your app supplies.
>
> **1. Create a Worker and File**
>
> Load the file before querying its asset metadata. Call these APIs from a main-actor async context.
>
> ```swift theme={null}
> let worker = try await Worker()
> let file = try await File(
> source: .local("my_rive_file", .main),
> worker: worker
> )
> ```
>
> **2. Choose and Load Assets**
>
> Iterate the file's assets and use their metadata to locate their bytes. This example matches bundled resources using each asset's `uniqueName` and `fileExtension`, skipping unknown asset types and resources that are not bundled.
>
> ```swift theme={null}
> for asset in try await file.getAssets() {
> if case .unknown = asset.type { continue }
> guard let url = Bundle.main.url(
> forResource: asset.uniqueName,
> withExtension: asset.fileExtension
> ) else { continue }
>
> let data = try await Task.detached {
> try Data(contentsOf: url)
> }.value
>
> // Decode and register the asset here, as shown below.
> }
> ```
>
> **3. Register Global Assets**
>
> Inside the loop, decode each asset with the worker and register it using `asset.uniqueName`. The worker applies it to files using that unique name.
>
> ```swift theme={null}
> switch asset.type {
> case .image:
> let image = try await worker.decodeImage(from: data)
> worker.addGlobalImageAsset(image, name: asset.uniqueName)
> case .font:
> let font = try await worker.decodeFont(from: data)
> worker.addGlobalFontAsset(font, name: asset.uniqueName)
> case .audio:
> let audio = try await worker.decodeAudio(from: data)
> worker.addGlobalAudioAsset(audio, name: asset.uniqueName)
> case .blob, .unknown:
> break
> }
> ```
>
> #### Complete Example
>
> This example loads bundled resources whose filenames match each asset's `uniqueName` plus its `fileExtension` (for example, `picture-47982.jpeg`). It skips assets without a matching bundled resource and leaves them unchanged.
>
> ```swift theme={null}
> @MainActor
> func loadFileWithAssets() async throws -> File {
> let worker = try await Worker()
> let file = try await File(
> source: .local("my_rive_file", .main),
> worker: worker
> )
>
> for asset in try await file.getAssets() {
> if case .unknown = asset.type { continue }
> guard let url = Bundle.main.url(
> forResource: asset.uniqueName,
> withExtension: asset.fileExtension
> ) else { continue }
>
> let data = try await Task.detached {
> try Data(contentsOf: url)
> }.value
>
> switch asset.type {
> case .image:
> let image = try await worker.decodeImage(from: data)
> worker.addGlobalImageAsset(image, name: asset.uniqueName)
> case .font:
> let font = try await worker.decodeFont(from: data)
> worker.addGlobalFontAsset(font, name: asset.uniqueName)
> case .audio:
> let audio = try await worker.decodeAudio(from: data)
> worker.addGlobalAudioAsset(audio, name: asset.uniqueName)
> case .blob, .unknown:
> break
> }
> }
>
> return file
> }
> ```
>
> Create your `Rive` and view from the returned file. You can also register replacements after displaying a file. Using the same unique name updates matching assets across files on that worker; use separate workers when those files need different replacements.
>
> ### Loading Hosted Assets
>
> The new runtime does not automatically fetch hosted assets. For an asset with `cdn` metadata, fetch its bytes from `baseURL` with `uuid` appended as a path component, then decode and register it using the same global asset APIs.
>
> For example, inside an asset loop, load hosted images with:
>
> ```swift theme={null}
> guard asset.type == .image,
> let cdn = asset.cdn,
> let baseURL = URL(string: cdn.baseURL)
> else { continue }
>
> let url = baseURL.appendingPathComponent(cdn.uuid)
> let (data, response) = try await URLSession.shared.data(from: url)
> guard let response = response as? HTTPURLResponse,
> (200..<300).contains(response.statusCode)
> else { throw URLError(.badServerResponse) }
>
> let image = try await worker.decodeImage(from: data)
> worker.addGlobalImageAsset(image, name: asset.uniqueName)
> ```
>
> ### Decoding native fonts
>
> In addition to font-file bytes, `decodeFont(from:)` accepts a platform font:
>
> ```swift theme={null}
> #if canImport(UIKit)
> let font = try await worker.decodeFont(from: UIFont.systemFont(ofSize: 12))
> #elseif canImport(AppKit)
> let font = try await worker.decodeFont(from: NSFont.systemFont(ofSize: 12))
> #endif
> worker.addGlobalFontAsset(font, name: fontAsset.uniqueName)
> ```
>
> Import `UIKit` or `AppKit` for the platform you target. The Rive text run controls the displayed font size. The decoded font can also be assigned to a `FontProperty`.
>
> ### Managing Global Assets
>
> The worker retains registered assets, so you do not need to keep a separate strong reference while they are registered. To remove a registration, use the corresponding API with the same unique name:
>
> ```swift theme={null}
> worker.removeGlobalImageAsset(name: imageAsset.uniqueName)
> worker.removeGlobalFontAsset(fontAsset.uniqueName)
> worker.removeGlobalAudioAsset(name: audioAsset.uniqueName)
> ```
> [tab] Legacy Runtime
>
> ### Examples
>
> * [(SwiftUI) Swap out images and fonts](https://github.com/rive-app/rive-ios/blob/main/Example-iOS/Source/Examples/SwiftUI/SwiftSimpleAssets.swift)
> * [(UIKit) Swap and cache images and fonts](https://github.com/rive-app/rive-ios/blob/main/Example-iOS/Source/Examples/Storyboard/CachedAssets.swift)
>
> ### Using the Asset Handler API
>
> When instantiating a `RiveViewModel` (or `RiveFile` directly), add a `customLoader` callback property to the list of parameters. This callback will be called for every asset the runtime detects from the `.riv` file on load, and the callback will be responsible for either handling the load of an asset at runtime or passing on the responsibility and giving the runtime a chance to load it otherwise.
>
> An instance where you may want to handle loading an asset is if an asset in the file is marked as **Referenced**, and you need to provide an actual asset to render for the graphic, as Rive does not embed it in the `.riv` and thus cannot load it.
>
> An instance where you may want to give the runtime a chance to load the asset is if the asset in the file is marked as **Hosted**, and want to pass the responsibility of loading it to the runtime (which will call into a Rive CDN to do so).
>
> ```swift theme={null}
> RiveViewModel(fileName: "simple_assets", loadCdn: false, customLoader: { (asset: RiveFileAsset, data: Data, factory: RiveFactory) -> Bool in
> // A simple check for a Rive file with one asset
> if (asset is RiveImageAsset){
> // picture-47982.jpeg can be exported with the .riv file from the Rive editor.
> // It is then included in the main bundle resources of the project
> guard let url = (.main as Bundle).url(forResource: "picture-47982", withExtension: "jpeg") else {
> fatalError("Failed to locate 'picture-47982' in bundle.")
> }
> guard let data = try? Data(contentsOf: url) else {
> fatalError("Failed to load \(url) from bundle.")
> }
> (asset as! RiveImageAsset).renderImage(
> factory.decodeImage(data)
> )
> return true;
> }
> return false;
> }).view()
> ```
>
> Your provided callback will be passed an `asset`, `data`, and a `factory`.
>
> * `asset` - Reference to a `RiveFileAsset` object. You'll use this reference to set a new Rive-specific asset for dynamically loaded content. If you wish to dynamically swap a given image/font over the lifetime of your view, you may want to cache this object. You can grab a number of properties from this object, such as:
>
> * `name()` - Name of the asset without the unique file identifier appended, (i.e. `picture.webp` instead of `picture-47982.webp`)
>
> * `uniqueFilename()` - Name of the asset with the unique file identifier, (i.e. `picture-47982.webp` instead of `picture.webp`)
>
> * `fileExtension()` - Name of the file extension (i.e. `"png"`)
>
> * `cdnBaseUrl()` - Name of the base URL for the CDN
>
> * `cdnUuid()` - Identifier for the resource in the Rive CDN. Useful to see if this has length so you can see if the asset is marked for grabbing from a Rive CDN (in which case, you can let the Rive runtime retrieve the asset, rather than your app logic)
>
> * `data` - Array of bytes for the asset. This is useful to determine if the asset is already embedded in the Rive file (aka, not marked as "referenced" in the editor)
>
> * `factory` - Utility with methods to transform an asset's bytes into a `RiveRenderImage` ,`RiveFont`, or `RiveAudio` which the `asset` object uses to render via `.renderImage(your-rive-render-image)` , `.font(your-rive-font)` , or `.audio(your-rive-audio)` . These assets are created by calling `factory.decodeImage(data)`, `factory.decodeFont(data)`, or `factory.decodeAudio(data)`
>
> **Important**: Note that the return value of the callback is a `boolean`, which is where you need to return:
>
> * `true` if you intend on handling and loading in an asset yourself, or
> * `false` if you do not want to handle asset loading for that given asset yourself, and attempt to have the runtime try to load the asset.
>
> **Example Usage**
>
> ```swift theme={null}
> import SwiftUI
> import RiveRuntime
>
> struct SimpleAssetReplacement: View {
> @StateObject private var riveInstance = RiveViewModel(fileName: "simple_assets", autoPlay: false, loadCdn: false, customLoader: { (asset: RiveFileAsset, data: Data, factory: RiveFactory) -> Bool in
> if (asset is RiveImageAsset) {
> guard let url = (.main as Bundle).url(forResource: "picture-47982", withExtension: "jpeg") else {
> fatalError("Failed to locate 'picture-47982' in bundle.")
> }
> guard let data = try? Data(contentsOf: url) else {
> fatalError("Failed to load \(url) from bundle.")
> }
> (asset as! RiveImageAsset).renderImage(
> factory.decodeImage(data)
> )
> return true;
> } else if (asset is RiveFontAsset) {
> guard let url = (.main as Bundle).url(forResource: "Inter-45562", withExtension: "ttf") else {
> fatalError("Failed to locate 'Inter-45562' in bundle.")
> }
> guard let data = try? Data(contentsOf: url) else {
> fatalError("Failed to load \(url) from bundle.")
> }
> (asset as! RiveFontAsset).font(
> factory.decodeFont(data)
> )
> return true;
> }
> return false;
> })
>
> var body: some View {
> riveInstance.view()
> }
> }
> ```
>
> ### Fonts
>
> When using a custom loader, referenced fonts can be loaded one of two ways: with raw data (from a file, as seen above), or with a `UIFont` / `NSFont`.\
> When using `UIFont` / `NSFont`, size, weight, and width of the supplied font is ignored. The font will be used as defined in the text run, rather than being overridden by the supplied font's styling.
>
> ```swift theme={null}
> import SwiftUI
> import RiveRuntime
>
> struct SimpleFontReplacement: View {
> @StateObject private var riveInstance = RiveViewModel(fileName: "simple_assets", autoPlay: false, loadCdn: false, customLoader: { (asset: RiveFileAsset, data: Data, factory: RiveFactory) -> Bool in
> if (asset is RiveFontAsset) {
> (asset as! RiveFontAsset).font(
> factory.decodeFont(UIFont.systemFont(ofSize: 12))
> )
> return true;
> }
> return false;
> })
>
> var body: some View {
> riveInstance.view()
> }
> }
> ```
>
> ### Images
>
> When loading assets for referenced images, you may need to scale local assets to the size of an image asset as defined in your Rive file. When using a custom loader, you can access the size of the referenced image via the `size` property of a `RiveImageAsset`.
>
> ```swift theme={null}
> import SwiftUI
> import RiveRuntime
>
> struct SimpleImageSizeReplacement: View {
> @StateObject private var riveInstance = RiveViewModel(fileName: "simple_assets", autoPlay: false, loadCdn: false, customLoader: { (asset: RiveFileAsset, data: Data, factory: RiveFactory) -> Bool in
> guard let imageAsset = asset as? RiveImageAsset else { return false }
> let requestedSize = imageAsset.size
> let image = UIImage(...)
> let resizedImage = resize(image, to: requestedSize)
> guard let pngData = resizedImage.pngData() else { return false }
> imageAsset.renderImage(
> factory.decodeImage(pngData)
> )
> return true
> }
> return false;
> }
>
> var body: some View {
> riveInstance.view()
> }
>
> ```
## Additional resources
[YouTube video player](https://www.youtube.com/embed/BrWBmZwouQQ)
# Logging
Source: https://rive.app/docs/runtimes/apple/logging
This Rive runtime includes logging capabilities to help with debugging. These logs are *only* for debugging purposes; nothing is sent over the network, and no personally identifiable information (PII) is logged.
The table below showcases the runtimes that support logging.
> [tab] New Runtime
>
> The new runtime supports logging via the `RiveLog` type. To enable logging, set the `RiveLog.logger` property to a `RiveLog.Logger` implementation. The new runtime defaults to no logging, which can be set at any time by setting `RiveLog.logger` to `RiveLog.none`. The new runtime ships with a default implementation that logs to the console, which can be set by using the `RiveLog.system(levels:)` helper function. When using the system logger, any logs that are not emitted at the levels specified will be suppressed.
>
> ```swift theme={null}
> // To enable the default logging implementation, which uses os.Logger
> RiveLog.logger = RiveLog.system(levels: .default)
>
> // To disable logging (the default)
> RiveLog.logger = RiveLog.none
> ```
>
> ### Levels
>
> Logs will be logged at various levels, which are inspired by `OSLogType` . These levels can be used to additionally filter logs to be logged at certain levels only. Available levels are:
>
> * **Notice**: important informational logs
> * **Debug**: commonly used to aid with debugging
> * **Trace**: highly detailed and potentially verbose diagnostic logs, including operations like advancing that may emit at least one log per frame
> * **Info**: logs that provide additional information
> * **Error**: used when an error occurs
> * **Warning**: used when a potential issue is detected
> * **Fault**: used when a severe error occurs
> * **Critical**: used when a fatal error occurs
>
> Convenience presets are also available:
>
> * **.default**: `.debug`, `.warning`, `.error`, `.fault`, `.critical`
> * **.all**: all levels (`.notice`, `.debug`, `.trace`, `.info`, `.error`, `.warning`, `.fault`, `.critical`)
>
> ### Custom Logger
>
> You can also implement your own custom logger by implementing the `RiveLog.Logger` protocol. This allows you to log to any desired sink, such as a file, a network endpoint, or a custom console.
>
> ```swift theme={null}
> nonisolated public protocol Logger: Sendable {
> nonisolated func notice(tag: Tag, _ message: @escaping () -> String)
> nonisolated func debug(tag: Tag, _ message: @escaping () -> String)
> nonisolated func trace(tag: Tag, _ message: @escaping () -> String)
> nonisolated func info(tag: Tag, _ message: @escaping () -> String)
> nonisolated func error(tag: Tag, error _: (any Error)?, _ message: @escaping () -> String)
> nonisolated func warning(tag: Tag, _ message: @escaping () -> String)
> nonisolated func fault(tag: Tag, _ message: @escaping () -> String)
> nonisolated func critical(tag: Tag, _ message: @escaping () -> String)
> }
> ```
>
> Once you have implemented your own logger, you can set it to the `RiveLog.logger` property.
>
> ```swift theme={null}
> RiveLog.logger = MyLogger()
> ```
> [tab] Legacy Runtime
>
> ```
> RiveLogger.isEnabled = true // Enable logging; false by default
> RiveLogger.levels = [.debug] // Filter logs; all by default
> RiveLogger.categories = [.viewModel] // Filter categories; all by default
> RiveLogger.isVerbose = true // Include verbose logs; false by default
> ```
# Migrating from the Legacy Rive Apple Runtime
Source: https://rive.app/docs/runtimes/apple/migrating-from-legacy
A guide to help you transition from the legacy Rive Apple runtime to the new runtime.
## Overview
The [new Rive Apple runtime](/docs/runtimes/apple/apple) is a **near-complete rewrite** of both the public API and the internal architecture. While conceptually most operations have an equivalent, the two APIs are incompatible. Any existing work in the legacy API that you would like to migrate must be rebuilt using the new API.
This guide covers:
1. [Shared Features](#shared-features) - Common operations and their equivalents.
2. [New Exclusive Features](#new-exclusive-features) - Capabilities only available in the new runtime.
3. [Legacy Exclusive Features](#legacy-exclusive-features) - Features no longer available in the new runtime and migration guidance.
> [!NOTE]
>
> This guide is not meant to be exhaustive as it would be redundant with existing general documentation. Please refer to the relevant sections of the documentation for more details on specific topics.
## Package and import
The new Apple runtime is available in the same Swift package and CocoaPods pod as the legacy runtime. Both runtime APIs are available in the same package, so you can import the runtime using the same import statement.
```swift theme={null}
import RiveRuntime
```
## Asynchronous APIs
The new runtime is built around Swift Concurrency. Most setup and query operations are asynchronous and should be called from an async context.
> [card]
>
> For more information, see the Apple getting started guide for end-to-end setup examples.
>
> [Open](/docs/runtimes/apple/apple#getting-started)
Common examples include:
* Creating a `Worker` asynchronously
* Creating `File` and `Rive` objects
* Creating artboards, state machines, and view model instances
```swift theme={null}
let worker = try await Worker()
let file = try await File(source: .local("my_file", Bundle.main), worker: worker)
let rive = try await Rive(file: file)
```
## Lifecycles and threading
The legacy runtime is effectively main-thread driven through `RiveViewModel` and `RiveView`.
The new runtime introduces `Worker` objects for background processing while still enforcing API calls on the main actor. In practice:
* `Worker` owns the background processing context
* `File` strongly references its `Worker`
* Out-of-band assets registered on a worker can be shared across files created with that worker
> [card]
>
> For more information, see the Threading section for additional details.
>
> [Open](/docs/runtimes/apple/apple#threading)
For most apps, a shared worker is recommended:
> [!NOTE]
>
> `AsyncShared` and the `Worker` extensions below are application-level helpers. They are not included with `RiveRuntime`.
```swift AsyncShared.swift theme={null}
/// Lazily creates and caches a value. Failed initialization can be retried.
@MainActor
final class AsyncShared {
private let makeValue: @MainActor () async throws -> Value
private var cachedValue: Value?
private var loadingTask: Task?
init(_ makeValue: @escaping @MainActor () async throws -> Value) {
self.makeValue = makeValue
}
func value() async throws -> Value {
if let cachedValue {
return cachedValue
}
let task = loadingTask ?? Task {
defer { loadingTask = nil }
let value = try await makeValue()
cachedValue = value
return value
}
loadingTask = task
return try await task.value
}
}
```
```swift AsyncShared+Worker.swift theme={null}
import RiveRuntime
extension AsyncShared where Value == Worker {
convenience init(configuration: Worker.Configuration = .init()) {
self.init {
try await Worker(configuration: configuration)
}
}
}
extension Worker {
@MainActor
private static let sharedWorker = AsyncShared()
@MainActor
private static let sharedGPUCanvasWorker = AsyncShared(
configuration: .init(enableGPUCanvas: true)
)
@MainActor
static func shared() async throws -> Worker {
try await sharedWorker.value()
}
@MainActor
static func sharedGPUCanvas() async throws -> Worker {
try await sharedGPUCanvasWorker.value()
}
}
```
```swift theme={null}
let worker = try await Worker.shared()
let file = try await File(source: ..., worker: worker)
let rive = try await Rive(file: file)
```
## Shared features
### Shared APIs
The main shared API area is fallback fonts through `RiveFont.fallbackFontsCallback`.
For fallback font types and behavior, see [Fallback Fonts](/docs/runtimes/fonts#fallback-fonts).
### RiveViewModel to Rive
Use the sections below as a migration map: [Loading a File from Disk](#loading-a-file-from-disk), [Creating a Rive View](#creating-a-rive-view), and [Data Binding](#data-binding). Legacy `RiveViewModel` flows in these areas become explicit `File` + `Rive` setup, then `RiveUIView`/SwiftUI representables in the new runtime.
### Loading a file from disk
#### Legacy Runtime
```swift theme={null}
// Cache this file for reuse
let file = try RiveFile(name: "my_rive_file")
let model = RiveModel(riveFile: file)
let viewModel = RiveViewModel(model)
```
#### New Runtime
```swift theme={null}
let worker = try await Worker.shared()
let file = try await File(source: .local("my_rive_file", Bundle.main), worker: worker)
let rive = try await Rive(file: file)
```
### Loading a file from URL
#### Legacy Runtime
```swift theme={null}
let webURL = URL(string: "https://example.com/my_rive_file.riv")!
let file = RiveFile(httpUrl: webURL, loadCdn: false, with: self)
let model = RiveModel(riveFile: file)
let viewModel = RiveViewModel(model)
```
#### New Runtime
```swift theme={null}
let worker = try await Worker.shared()
let webURL = URL(string: "https://example.com/my_rive_file.riv")!
let file = try await File(
source: .url(webURL),
worker: worker
)
let rive = try await Rive(file: file)
```
### Loading a file from data (bytes)
#### Legacy Runtime
```swift theme={null}
let data: Data = ...
let file = try RiveFile(data: data, loadCdn: false)
let model = RiveModel(riveFile: file)
let viewModel = RiveViewModel(model)
```
#### New Runtime
Use the `.data` file source when your `.riv` bytes are already available in memory.
```swift theme={null}
let worker = try await Worker.shared()
let data: Data = ...
let file = try await File(source: .data(data), worker: worker)
let rive = try await Rive(file: file)
```
### Tracking loading and error state
For common setup operations (loading files, creating artboards, creating state machines), the migration pattern is:
* Legacy runtime: many lookup APIs return optionals (`nil` on failure), so handle with `guard let` / fallback logic.
* New runtime: APIs throw errors, so use `do/catch`.
#### Legacy Runtime
Legacy APIs commonly return `nil` for lookup/create-style operations:
```swift theme={null}
let file = try RiveFile(name: "my_rive_file")
guard let artboard = file.artboard() else {
// Handle missing artboard
return
}
guard let stateMachine = artboard.defaultStateMachine() else {
// Handle missing state machine
return
}
```
#### New Runtime
New runtime APIs throw errors, so failure handling moves to `do/catch`:
```swift theme={null}
do {
let worker = try await Worker.shared()
let file = try await File(source: .local("my_rive_file", Bundle.main), worker: worker)
let artboard = try await file.createArtboard("My Artboard")
let stateMachine = try await artboard.createStateMachine("My State Machine")
let rive = try await Rive(file: file, artboard: artboard, stateMachine: stateMachine)
} catch {
// Handle file/artboard/state machine setup errors
}
```
This pattern applies equally in UIKit and SwiftUI. The key migration change is optional unwrapping in legacy vs error catching in the new runtime.
### Choosing an Artboard and State Machine
> [card]
>
> For more information, see artboards documentation for more details.
>
> [Open](/docs/runtimes/artboards)
> [card]
>
> For more information, see state machines documentation for more details.
>
> [Open](/docs/runtimes/state-machines)
#### Legacy Runtime
```swift theme={null}
let file = try RiveFile(name: "my_rive_file")
let model = RiveModel(riveFile: file)
model.setArtboard("My Artboard")
model.setStateMachine("My State Machine")
```
#### New Runtime
```swift theme={null}
let worker = try await Worker.shared()
let file = try await File(source: .local("my_rive_file", Bundle.main), worker: worker)
let artboard = try await file.createArtboard("My Artboard")
let stateMachine = try await artboard.createStateMachine("My State Machine")
let rive = try await Rive(file: file, artboard: artboard, stateMachine: stateMachine)
```
### Creating a Rive view
#### Legacy Runtime
```swift theme={null}
let viewModel = RiveViewModel(...)
// UIKit
let riveView = viewModel.createRiveView()
// SwiftUI
var body: some View {
viewModel.view()
}
```
#### New Runtime
```swift theme={null}
let worker = try await Worker.shared()
let file = try await File(source: ..., worker: worker)
let rive = try await Rive(file: file)
// UIKit (sync object already available)
let riveView = RiveUIView(rive: rive)
// UIKit (async loading)
let riveView = RiveUIView(rive: {
let worker = try await Worker.shared()
let file = try await File(source: ..., worker: worker)
return try await Rive(file: file)
})
// SwiftUI
var body: some View {
RiveUIViewRepresentable(rive: rive)
}
// SwiftUI (async)
var body: some View {
AsyncRiveUIViewRepresentable {
let worker = try await Worker.shared()
let file = try await File(source: ..., worker: worker)
return try await Rive(file: file)
}
}
```
### Setting Fit and Alignment
> [card]
>
> For more information, see the layout docs for all fit and alignment options.
>
> [Open](/docs/runtimes/layout#apple)
#### Legacy Runtime
```swift theme={null}
let viewModel = RiveViewModel(
fileName: "my_rive_file",
fit: .contain,
alignment: .center
)
// Update at runtime
viewModel.fit = .fitWidth
viewModel.alignment = .topCenter
```
To use artboard layout sizing in the legacy runtime:
```swift theme={null}
let viewModel = RiveViewModel(fileName: "my_rive_file")
viewModel.fit = .layout
viewModel.layoutScaleFactor = RiveViewModel.layoutScaleFactorAutomatic // default behavior
// Or explicitly set a scale factor
viewModel.layoutScaleFactor = 2.0
```
#### New Runtime
```swift theme={null}
let worker = try await Worker.shared()
let file = try await File(source: .local("my_rive_file", Bundle.main), worker: worker)
var rive = try await Rive(file: file, fit: .contain(alignment: .center))
// Update at runtime
rive.fit = .fitWidth(alignment: .topCenter)
```
To use artboard layout sizing in the new runtime:
```swift theme={null}
let worker = try await Worker.shared()
let file = try await File(source: .local("my_rive_file", Bundle.main), worker: worker)
var rive = try await Rive(file: file, fit: .layout(scaleFactor: .automatic))
// Or explicitly set a scale factor
rive.fit = .layout(scaleFactor: .explicit(2.0))
```
### Default Layout Scale Factor
When using layout fit, both runtimes support automatic and explicit scale factors.
#### Legacy Runtime
Use `RiveViewModel.layoutScaleFactorAutomatic` (default) or set an explicit numeric value on `layoutScaleFactor`.
#### New Runtime
Use `.layout(scaleFactor: .automatic)` or `.layout(scaleFactor: .explicit(...))` on `Rive.fit`.
### View Models
> [card]
>
> For more information, see the data binding docs for complete view model instance APIs.
>
> [Open](/docs/runtimes/data-binding)
#### Legacy Runtime
In legacy, view models are queried from `RiveFile`, then instances are created from that queried view model.
```swift theme={null}
let riveViewModel = RiveViewModel(...)
let file = riveViewModel.riveModel!.riveFile
guard let viewModel = file.viewModelNamed("My View Model") else {
return
}
// Create blank/default/named instances from the queried view model
let blankInstance = viewModel.createInstance()
let defaultInstance = viewModel.createDefaultInstance()
let namedInstance = viewModel.createInstance(fromName: "My Instance")
```
#### New Runtime
In the new runtime, the view model is represented as source metadata passed directly into `createViewModelInstance`.
```swift theme={null}
let worker = try await Worker.shared()
let file = try await File(source: .local("my_rive_file", Bundle.main), worker: worker)
// By explicit view model name
let blankInstance = try await file.createViewModelInstance(
from: .blank(from: .name("My View Model"))
)
let defaultInstance = try await file.createViewModelInstance(
from: .name("My View Model")
)
let namedInstance = try await file.createViewModelInstance(
from: .name("My Instance", from: .name("My View Model"))
)
```
You can also source the view model from an artboard default:
```swift theme={null}
let artboard = try await file.createArtboard()
let defaultFromArtboard = try await file.createViewModelInstance(
from: .viewModelDefault(from: .artboardDefault(artboard))
)
```
### View Model instance properties
#### Legacy Runtime
Legacy data-binding instances expose typed property objects that you query from the instance.
```swift theme={null}
let riveViewModel = RiveViewModel(...)
var instance: RiveDataBindingViewModel.Instance!
riveViewModel.riveModel?.enableAutoBind { boundInstance in
instance = boundInstance
}
guard let stringProperty = instance.stringProperty(fromPath: "path/to/string") else {
return
}
// Set
stringProperty.value = "Hello, Rive"
// Get
let currentValue = stringProperty.value
```
#### New Runtime
The new runtime uses typed path descriptors with methods on `ViewModelInstance` for set/get/observe.
```swift theme={null}
let worker = try await Worker.shared()
let file = try await File(source: .local("my_rive_file", Bundle.main), worker: worker)
let viewModelInstance = try await file.createViewModelInstance(
from: .name("My View Model")
)
let stringProperty = StringProperty(path: "path/to/string")
// Set
viewModelInstance.setValue(of: stringProperty, to: "Hello, Rive")
// Get current value
let currentValue = try await viewModelInstance.value(of: stringProperty)
// Observe changes over time
let valueStream = viewModelInstance.valueStream(of: stringProperty)
for try await updatedValue in valueStream {
print(updatedValue)
}
```
### Bindable Artboards
#### Legacy Runtime
Legacy artboard property binding uses a bindable artboard wrapper type.
```swift theme={null}
let instance: RiveDataBindingViewModel.Instance = ...
guard let artboardProperty = instance.artboardProperty(fromPath: "path/to/artboard") else {
return
}
let components = try RiveFile(name: "component_library")
guard let bindableArtboard = components.bindableArtboard(withName: "My Artboard") else {
return
}
artboardProperty.setValue(bindableArtboard)
```
#### New Runtime
The new runtime binds artboards with a typed property descriptor and `setValue` on the instance.
```swift theme={null}
let worker = try await Worker.shared()
let file = try await File(source: .local("my_rive_file", Bundle.main), worker: worker)
let viewModelInstance = try await file.createViewModelInstance(.viewModelDefault(from: .name("My View Model")))
let artboardProperty = ArtboardProperty(path: "path/to/artboard")
let artboard = try await file.createArtboard("My Artboard")
viewModelInstance.setValue(of: artboardProperty, to: artboard)
```
### Data Binding
> [card]
>
> For more information, see the data binding docs for full API coverage.
>
> [Open](/docs/runtimes/data-binding)
#### Legacy Runtime
```swift theme={null}
let file = try RiveFile(...)
let model = RiveModel(riveFile: file)
model.enableAutoBind { instance in
self.viewModelInstance = instance
instance.stringProperty(fromPath: "...").value = "Hello, Rive"
}
```
You can also manually bind a specific instance:
```swift theme={null}
let file = try RiveFile(...)
guard let artboard = file.artboard() else { return }
guard let stateMachine = artboard.defaultStateMachine() else { return }
guard let viewModel = file.defaultViewModel(for: artboard) else { return }
guard let instance = viewModel.createDefaultInstance() else { return }
stateMachine.bindViewModelInstance(instance) // bound successfully
```
#### New Runtime
Use `Rive(file:)` when authored defaults are sufficient and you do not need to access their properties. For programmatic access, replace the legacy auto-bind callback with explicit instance creation and retain the instance in your app's model:
```swift theme={null}
let worker = try await Worker.shared()
let file = try await File(source: .local("my_rive_file", Bundle.main), worker: worker)
let artboard = try await file.createArtboard()
let instance = try await file.createViewModelInstance(
.viewModelDefault(from: .artboardDefault(artboard))
)
let stateMachine = try await artboard.createStateMachine(binding: instance)
let rive = try await Rive(file: file, artboard: artboard, stateMachine: stateMachine)
instance.setValue(of: StringProperty(path: "path/to/string"), to: "Hello, Rive")
```
Create these components from a `@MainActor` async context. Keep the instance reference for later property access and observation. For global bindings, see [Global View Models](/docs/runtimes/apple/data-binding#global-view-models).
#### Updating existing concurrency runtime code
The global view model update also changes APIs in the new concurrency runtime:
| Previous API | Replacement |
| - | - |
| `Rive(file: file, dataBind: .auto)` | `Rive(file: file)` for authored defaults, or explicit instance creation for property access |
| `Rive(file: file, dataBind: .instance(instance))` | `artboard.createStateMachine(binding: instance)`, then pass that artboard and state machine to `Rive` |
| `Rive(..., dataBind: .none)` | Pass the configured artboard and state machine to `Rive` without `dataBind` |
| `rive.viewModelInstance` | Retain the instance you create and bind |
| `stateMachine.bindViewModelInstance(instance)` | `try await stateMachine.bindViewModelInstances(main: instance)` |
| `instance.dirtyStream()` for redraws | Automatic `RiveController` observation of bound instances |
> [!WARNING]
>
> Calls such as `Rive(file:)` can continue compiling while changing behavior: the new initializers leave the deprecated `viewModelInstance` getter `nil`. Neither `Rive` nor `StateMachine` exposes getters for automatically bound instances. Removing `dataBind:` alone is insufficient if your code accesses that getter.
`Rive(file:)` and `Rive(file:artboard:)` create a state machine and bind authored defaults. `Rive(file:artboard:stateMachine:)` uses the supplied state machine without rebinding. State machine creation already binds available defaults, so omitting `dataBind` is not a way to disable that initial binding. Likewise, deprecated `.none` only skips binding in the legacy initializer; it does not undo existing bindings.
For a temporary compatibility bridge, explicitly select the deprecated initializer:
```swift theme={null}
let rive = try await Rive(file: file, dataBind: .auto)
let instance = rive.viewModelInstance // Legacy-created main instance, when available.
```
`DataBind`, this initializer, and the getter are all deprecated. The getter is an initialization snapshot: later rebinding does not update it. Prefer the explicit setup above for new code.
#### Setting up instances for your app
Create the instances you need, bind them, and keep their references in your app's model. This example uses a default main instance and a "Light" instance from the global "Theme" view model. Run setup in a `@MainActor` async context, using the same file and worker for all components.
```swift theme={null}
let artboard = try await file.createArtboard()
let main = try await file.createViewModelInstance(
.viewModelDefault(from: .artboardDefault(artboard))
)
let theme = try await file.createViewModelInstance(
.name("Light", from: .name("Theme"))
)
let stateMachine = try await artboard.createStateMachine(binding: main) {
("Theme", theme)
}
let rive = try await Rive(file: file, artboard: artboard, stateMachine: stateMachine)
```
Keep `rive`, `main`, and `theme`. Set any initial property values before presenting the view. See [Global View Models](/docs/runtimes/apple/data-binding#global-view-models) for replacing bindings and switching themes.
#### Optional auto-bind helper
For default instances, add this extension to your app. It returns `Rive` together with the main and global instances:
```swift theme={null}
extension Rive {
@MainActor
static func autoBound(
file: File,
artboardName: String? = nil,
stateMachineName: String? = nil
) async throws -> (
rive: Rive,
main: ViewModelInstance,
globals: [String: ViewModelInstance]
) {
let artboard = try await file.createArtboard(artboardName)
let main = try await file.createViewModelInstance(
.viewModelDefault(from: .artboardDefault(artboard))
)
var globals: [String: ViewModelInstance] = [:]
for name in try await file.getGlobalViewModelNames() {
globals[name] = try await file.createViewModelInstance(
.viewModelDefault(from: .name(name))
)
}
let stateMachine = try await artboard.createStateMachine(stateMachineName, binding: main) {
for (name, instance) in globals {
(name, instance)
}
}
let rive = try await Rive(file: file, artboard: artboard, stateMachine: stateMachine)
return (rive, main, globals)
}
}
```
This is an app-owned helper, not a runtime API. It requires a default main instance and a default instance for each global; missing defaults throw. Without globals, the dictionary is empty.
Call it from a `@MainActor` async context and retain `autoBound`:
```swift theme={null}
let autoBound = try await Rive.autoBound(file: file)
autoBound.main.setValue(of: StringProperty(path: "title"), to: "Welcome")
let theme = autoBound.globals["Theme"]
let riveView = RiveUIView(rive: autoBound.rive)
```
If you replace a binding later, update your stored instance reference after binding succeeds.
### Updating a Data Bind unsettles the State Machine
Legacy and new runtime behavior differ here:
* Legacy: after changing a data bound property, you typically call `play()` to advance/unsettle and apply the change if the graphic has settled.
* New runtime: setting a data bound property no longer requires an explicit `play()` call, simplifying the API.
Best practice for migration: if you need initial values, set them **before** creating and presenting a view.
This avoids showing default values for a frame before your app-provided values are applied.
#### Legacy Runtime
When updating a bound value after the view is created, keep a reference to the instance and call `play()` after mutation:
```swift theme={null}
let viewModel = RiveViewModel(...)
var instance: RiveDataBindingViewModel.Instance?
viewModel.riveModel?.enableAutoBind { boundInstance in
instance = boundInstance
}
let riveView = viewModel.createRiveView()
instance?.stringProperty(fromPath: "path/to/string")?.value = "Updated Value"
viewModel.play() // Required to advance/unsettle after mutation
```
#### New Runtime
In the new runtime, update the bound value after the view is created. No explicit `play()` call is needed.
```swift theme={null}
let worker = try await Worker.shared()
let file = try await File(source: .local("my_rive_file", Bundle.main), worker: worker)
let instance = try await file.createViewModelInstance(.viewModelDefault(from: .name("My View Model")))
let property = StringProperty(path: "path/to/string")
let artboard = try await file.createArtboard()
let stateMachine = try await artboard.createStateMachine(binding: instance)
let rive = try await Rive(file: file, artboard: artboard, stateMachine: stateMachine)
let riveView = RiveUIView(rive: rive)
instance.setValue(of: property, to: "Updated Value") // Applies without play()
```
### Playing and pausing
> [card]
>
> For more information, see playback controls in the Apple runtime guide.
>
> [Open](/docs/runtimes/apple/apple#playing--pausing)
#### Legacy Runtime
```swift theme={null}
let viewModel = RiveViewModel(fileName: "...")
viewModel.pause() // or play() to resume
```
#### New Runtime
```swift theme={null}
let rive = try await Rive(...)
let riveView = RiveUIView(rive: rive)
riveView.isPaused = true // or false to resume
// SwiftUI
RiveUIViewRepresentable(rive: rive)
.paused(true)
```
### Frame rate
> [card]
>
> For more information, see frame rate controls and ProMotion notes.
>
> [Open](/docs/runtimes/apple/apple#frame-rate)
#### Legacy Runtime
```swift theme={null}
let viewModel = RiveViewModel(fileName: "...")
viewModel.setPreferredFramesPerSecond(preferredFramesPerSecond: 30)
```
#### New Runtime
```swift theme={null}
let rive = try await Rive(...)
let riveView = RiveUIView(rive: rive)
riveView.frameRate = .fps(30)
// or
riveView.frameRate = .range(minimum: 30, maximum: 60)
// or
riveView.frameRate = .default
```
### Loading referenced assets
#### Legacy Runtime
The legacy runtime uses a `customLoader` callback to inspect assets and provide their contents while loading a file.
```swift theme={null}
let viewModel = RiveViewModel(fileName: "my_rive_file") { asset, _, factory in
if let imageAsset = asset as? RiveImageAsset {
let decodedImage = factory.decodeImage(Data(...))
imageAsset.renderImage(decodedImage)
return true
} else if let fontAsset = asset as? RiveFontAsset {
let decodedFont = factory.decodeFont(Data(...))
fontAsset.font(decodedFont)
return true
} else if let audioAsset = asset as? RiveAudioAsset {
let decodedAudio = factory.decodeAudio(Data(...))
audioAsset.audio(decodedAudio)
return true
} else {
return false
}
}
```
#### New Runtime
Use `File.getAssets()` and the worker's global asset APIs in place of `customLoader`. Create the file, inspect its asset metadata, then decode and register the assets your app supplies. You no longer need to know their unique names before loading the file.
This example replaces an image selected by its authored name:
```swift theme={null}
let worker = try await Worker.shared()
let file = try await File(
source: .local("my_rive_file", .main),
worker: worker
)
for asset in try await file.getAssets() {
guard asset.type == .image, asset.name == "picture.jpeg" else { continue }
guard let url = Bundle.main.url(
forResource: asset.uniqueName,
withExtension: asset.fileExtension
) else { throw URLError(.fileDoesNotExist) }
let data = try await Task.detached {
try Data(contentsOf: url)
}.value
let image = try await worker.decodeImage(from: data)
worker.addGlobalImageAsset(image, name: asset.uniqueName)
}
let rive = try await Rive(file: file)
```
Use `asset.uniqueName` as the registration key. The replacement applies to this file and any other files using that unique name on the same worker, including files loaded later. You can also register or replace global assets after the file is displayed.
For fonts and audio, use `decodeFont(from:)` / `addGlobalFontAsset(_:name:)` and `decodeAudio(from:)` / `addGlobalAudioAsset(_:name:)`. There is no callback return value: your app chooses which assets to register after inspecting the metadata.
See [Loading Assets](/docs/runtimes/apple/loading-assets) for the full metadata reference, examples for all three asset types, and hosted asset loading.
### Logging
> [card]
>
> For more information, see the logging guide for shared concepts and filtering options.
>
> [Open](/docs/runtimes/logging)
#### Legacy Runtime
```swift theme={null}
RiveLogger.isEnabled = true
RiveLogger.levels = [.debug, .error]
RiveLogger.categories = [.stateMachine, .artboard, .viewModel]
RiveLogger.isVerbose = true
```
#### New Runtime
```swift theme={null}
RiveLog.logger = RiveLog.system(levels: .default)
// Or use your own implementation of RiveLog.Logger
RiveLog.logger = MyLogger()
// Disable logs
RiveLog.logger = RiveLog.none
```
### Fallback fonts
Both runtimes support fallback fonts.
* `RiveFont.fallbackFontsCallback` remains available
* Existing fallback font strategies can be reused across both runtimes
```swift theme={null}
RiveFont.fallbackFontsCallback = { style in
switch style.weight {
case .thin:
return [RiveFallbackFontDescriptor(weight: .thin)]
case .bold:
return [RiveFallbackFontDescriptor(weight: .bold)]
default:
return [RiveFallbackFontDescriptor()]
}
}
```
## New exclusive features
### Worker-based concurrency
The new runtime introduces `Worker` as an explicit concurrency primitive. This is a substantial change from the legacy runtime, which did not expose an equivalent concept.
Benefits include:
* Better control over background processing
* Shared global asset registration per worker
* More predictable architecture when rendering multiple files
A shared worker is usually the best default. Use multiple workers only when you need additional parallel processing, such as when rendering multiple heavyweight graphics.
### Async initialization APIs
The new runtime supports async constructors and async view wrappers (`RiveUIView` with async closure and `AsyncRiveUIViewRepresentable`) to better model real-world loading flows.
The async wrappers are useful when a view must own its own loading lifecycle. If you need reuse and caching across screens, prefer creating and storing `File`/`Rive` objects at a higher level.
## Legacy exclusive features
Some features in the legacy runtime are intentionally not present in the new runtime.
### Automatic CDN asset loading
The legacy runtime can fetch hosted assets automatically through `loadCdn`. In the new runtime, query `File.getAssets()` and use each asset's optional `cdn` metadata to fetch its bytes yourself, then decode and register it with the worker using `asset.uniqueName`. See [Loading Hosted Assets](/docs/runtimes/apple/loading-assets#loading-hosted-assets).
### State Machine Inputs
The legacy runtime supports state machine input APIs directly. The new runtime does not expose equivalent input APIs, and migration should move to data binding properties (number, boolean, string, trigger-style interactions).
The Rive Editor provides a conversion tool in **Menu > Convert Inputs to ViewModels** that can help with initial migration.
There are no current plans to reintroduce direct state machine input APIs in the new runtime.
### Events
The legacy runtime supports event listeners. The new runtime does not currently expose an equivalent event listener API. For many migration scenarios, a data binding contract is the recommended replacement for app-runtime communication.
Simple event-like behavior can often be modeled with trigger-oriented view model properties.
There are no current plans to reintroduce legacy-style event listener APIs in the new runtime.
### Linear animations
Legacy integrations can directly target linear animations. In migration, graphics are required to contain a state machine.
For existing files that rely on linear animations, create a state machine in the Editor with a single state that plays the desired animation.
### Observing State Machine state
Legacy integrations often used state-change delegate callbacks (for example, `RiveStateDelegate.stateChange(...)`) to react to animation state.
The new runtime does not expose a direct state-name observation API in this guide. For migration, model those app-facing signals as data-binding properties and observe them from the bound instance.
```swift theme={null}
let property = StringProperty(path: "path/to/state_signal")
let stream = viewModelInstance.valueStream(of: property)
for try await value in stream {
// React to state-like changes emitted from the Rive file
}
```
### Getting by index
Where possible, prefer named queries and explicit sources (for example, `ViewModelSource` and named artboard/state machine queries) over index-based coupling.
# Migration Guides
Source: https://rive.app/docs/runtimes/apple/migration-guides
Migrating between major versions of the Apple runtime
> [accordion] Migrating from 5.x.x to 6.x.x
>
> > [!WARNING]
> >
> > Contains a breaking change
>
> ## Rive Renderer
>
> ### RendererType
>
> `riveRenderer` is now the new default renderer type, and `skiaRenderer` has been removed. If you were previously explicitly setting the renderer type to Skia, then you will have to [specify a new renderer](/docs/runtimes/choose-a-renderer/), or use the new default Rive Renderer (our recommendation).
>
> ## Package Size
>
> Rive's iOS runtime is now \~57% smaller, at \~3.3mb, compared to \~7.6mb prior to v6.0.0.
> [accordion] Migrating from 4.x.x to 5.x.x
>
> > [!NOTE]
> >
> > No breaking API changes!
>
> There should be no major changes to your code to migrate to `v5.x.x`. Starting in `v5.x.x`, a new text engine dependency to support the new Rive [Text](/docs/runtimes/apple/text) feature, so you may see a slight bump in the size of the package to account for this.
> [accordion] Migrating from 3.x.x to 4.x.x
>
> There should be no major changes to your code to migrate to `v4.x.x`. Starting in `v4.0.1`, you can use the same runtime package `rive-ios` to install `RiveRuntime` into native `macOS` applications. The API usage of `RiveRuntime` in iOS and macOS applications should remain the same. If you do find any discrepancies or issues, please log an issue to [https://github.com/rive-app/rive-ios/issues](https://github.com/rive-app/rive-ios/issues).
>
> [https://github.com/rive-app/rive-ios/issues](https://github.com/rive-app/rive-ios/issues)
> [accordion] Migrating from 2.x.x to 3.x.x
>
> Migrating to v3 of the Apple runtime should be fairly straightforward. See the sections below on concerns you may need to look out for to change to your app if you upgrade.
>
> ## Enums Naming
>
> Starting in v3, the Layout option enums have changed to match enum naming conventions from the other runtimes for consistency. See below for what you should change `Fit` and `Alignment` options to. There are also a few other enums for parameters that have changed slightly regarding loop modes and direction.
>
> | Fit | Before | After |
> | - | - | - |
> | Fill | `.fitFill` | `.fill` |
> | Contain | `.fitContain` | `.contain` |
> | Cover | `.fitCover` | `.cover` |
> | Fit Width | `.fitFitWidth` | `.fitWidth` |
> | Fit Height | `.fitFitHeight` | `.fitHeight` |
> | Scale Down | `.fitScaleDown` | `.scaleDown` |
> | None | `.fitNone` | `.noFit` |
>
> | Alignment | Before | After |
> | - | - | - |
> | Top Left | `.alignmentTopLeft` | `.topLeft` |
> | Top Center | `.alignmentTopCenter` | `.topCenter` |
> | Top Right | `.alignmentTopRight` | `.topRight` |
> | Center Left | `.alignmentCenterLeft` | `.centerLeft` |
> | Center | `.alignmentCenter` | `.center` |
> | Center Right | `.alignmentCenterRight` | `.centerRight` |
> | Bottom Left | `.alignmentBottomLeft` | `.bottomLeft` |
> | Bottom Center | `.alignmentBottomCenter` | `.bottomCenter` |
> | Bottom Right | `.alignmentBottomRight` | `.bottomRight` |
>
> | Loop Mode | Before | After |
> | - | - | - |
> | One Shot | `loopOneShot` | `oneShot` |
> | Loop | `loopLoop` | `loop` |
> | Ping Pong | `loopPingPong` | `pingPong` |
> | Auto | `loopAuto` | `autoLoop` |
>
> | Direction | Before | After |
> | - | - | - |
> | Backwards | `directionBackwards` | `backwards` |
> | Forwards | `directionForwards` | `forwards` |
> | Auto | `directionAuto` | `autoDirection` |
>
> ## Default playing behavior
>
> One changed default behavior in v3 is what plays in the Rive canvas. Before v3, if no state machine or specific animation was specified when setting up the `RiveViewModel`, the first animation made in the Rive file would play.
>
> With v3, if no state machine or specific animation is specified, the first state machine (if one is created) in the Rive file will play. So if you prefer to keep your existing default behavior of the first animation, simply set the `animationName` property on `RiveViewModel` when creating it.
> [accordion] Migrating from 1.x.x to 2.x.x
>
> > [!NOTE]
> >
> > The Rive Apple runtime has a different API in 2.x.x from 1.x.x that allows for a unified internal model that supports both Storyboard/UIKit and SwiftUI usage.
>
> There are now 3 main pieces of the Rive API to be familiar with for iOS development:
>
> * `RiveView` - Core logic for building and manipulating Rive views
> * `RiveModel` - Describes the configuration model for Rive objects
> * `RiveViewModel` - The main class to interface with when integrating rive, creating a Rive view in some instances. It provides a high-level API that makes it simple to do actions like instantiation, animation playback, layout changes, and more.
>
> We recommend migrating to the latest version of v2.x.x as soon as possible, and you can find steps on this below:
>
> ## UIKit
>
> In v1.x.x, you may have loaded in a Rive file in the following snippet pattern:
>
> ```javascript theme={null}
> class SimpleAnimationViewController: UIViewController {
> let url = "https://cdn.rive.app/animations/truck.riv"
>
> override public func loadView() {
> super.loadView()
>
> let view = RiveView()
> guard let riveFile = RiveFile(httpUrl: url, with: view) else {
> fatalError("Unable to load RiveFile")
> }
> try? view.configure(riveFile)
>
> self.view = view
> }
> }
> ```
>
> This pattern interfaced with 2 Rive APIs, `RiveFile` and `RiveView`. With v2.x.x, the pattern becomes simpler, interfacing with one `RiveViewModel`.
>
> ```javascript theme={null}
> class SimpleAnimationViewController: UIViewController {
> var viewModel = RiveViewModel(fileName: "truck")
>
> override func viewWillAppear(_ animated: Bool) {
> let riveView = viewModel.createRiveView()
> view.addSubview(riveView)
> riveView.frame = view.frame
> }
> }
> ```
>
> Here's another example:
>
> ```javascript theme={null}
> class MultipleAnimationsController: UIViewController, RivePLayerDelegate {
> @IBOutlet weak var riveView: RiveView!
>
> var viewModel = RiveViewModel(
> fileName: "multiple_animations",
> animationName: "Animation 1",
> artboardName: "Animation Playground"
> )
>
> override func viewDidLoad() {
> viewModel.setView(riveView)
> }
> }
> ```
>
> See subsequent runtime pages for new usage of animation playback and layouts with UIKit.
>
> ### State Machine Usage
>
> In v1.x.x, you would set state machine input values with the following API: `riveView.setNumberState("Number Test", inputName: "Level", value: 2.0)`
>
> `riveView.setBooleanState("Boolean Test", inputName: "isSuccess", value: true)`
>
> `riveView.fireState("Trigger Test", inputName: "trigFail")`
>
> In v2.x.x, some of the input state setters have been consolidated and renamed. Additionally, the setters are called on the `RiveViewModel` which has the context of the state machine that was instantiated, so there is no longer a need to pass it the name: viewModel`.setInput("Level", value: 2.0)`
>
> viewModel`.setInput("isSuccess", value: true)`
>
> `viewModel.triggerInput("trigFail")`
>
> ### Delegates
>
> In the past, you may have implemented various functions that came with some of the following delegates: `LoopDelegate` , `PlayDelegate`, `PauseDelegate`, `StopDelegate`, and `StateChangeDelegate`. The various functions that get implemented on your end (i.e `loop`, `play`, `pause`, `stateChange`, etc.) have been consolidated under 2 main delegates, `RivePlayerDelegate` and `RiveStateMachineDelegate` with a slightly different function to override.
>
> See the following list of delegates for methods to hook into:
>
> * `RivePlayerDelegate` - Hook into animation and state machine lifecycle events
> * `player`: `(loopedWithModel riveModel: RiveModel?, type: Int) {}`
> * `player`: `(playedWithModel riveModel: RiveModel?) {}`
> * `player`: `(pausedWithModel riveModel: RiveModel?) {}`
> * `player`: `(stoppedWithModel riveModel: RiveModel?) {}`
> * `RiveStateDelegate` - Hook into state changes on a state machine lifecycle
> * `stateChange`: `(_ stateMachineName: String, _ stateName: String) {}`
>
> ## SwiftUI
>
> v1.x.x had a small wrapper around the existing `RiveView` class to help support Rive in the context of applications written in SwiftUI. v2.x.x now supports a more robust pattern for consuming Rive in your SwiftUI applications that fixes several bugs with the existing wrapper approach and provides a closer experience with the new pattern of SwiftUI.
>
> See subsequent runtime pages to learn how to control animation playback, state machines, and more with v2.x.x
>
> ```javascript theme={null}
> struct AnimationView: View {
> var body: some View {
> RiveViewModel(fileName: "cool_rive_animation").view()
> }
> }
> ```
# Playing Audio
Source: https://rive.app/docs/runtimes/apple/playing-audio
Playing Rive audio events
To learn more on how to add audio to your Rive file, see [Audio Events](/docs/editor/events/audio-events).
## Embedded assets
Embedded assets require no additional work to play audio.
## Referenced assets
Referenced assets require a little bit more work to play audio. Audio will still automatically play, but the audio file(s) must be loaded when a Rive runtime attempts to play audio.
For more information, see [Loading Assets](/docs/runtimes/apple/loading-assets).
## Audio settings
On iOS, playing audio will respect your `AVAudioSession` shared instance settings. For more information, see [Apple's documentation](https://developer.apple.com/documentation/avfaudio/avaudiosession) on `AVAudioSession`. Using this, you can choose to mix audio, duck audio, and more. You can update your shared instance early in your app lifecycle if you would like to ensure all Rive audio plays with the correct settings.
```swift IOS theme={null}
// Example: Ignore the silent switch, and mix with other audio
let category: AVAudioSession.Category = .playback
let options: AVAudioSession.CategoryOptions = [.mixWithOthers]
AVAudioSession.sharedInstance().setCategory(category, options: options)
```
## Setting volume
An artboard is capable of setting its volume. A parent artboard will set the volume of all component instances; however, setting a component's volume will **not** update the parent's volume.
> [tab] New Runtime
>
> Once you have created an `Artboard`, you can set its volume with `setVolume(_:)` and read the current volume with `volume()`. Volume is propagated to all nested artboards.
>
> ```swift theme={null}
> let worker = try await Worker()
> let file = try await File(source: .local("my_rive_file", Bundle.main), worker: worker)
> let artboard = try await file.createArtboard()
>
> // `setVolume(_:)` is a @MainActor method on `Artboard`.
> // Set the artboard's volume to 50% (0.0 = muted, 1.0 = full volume)
> artboard.setVolume(0.5)
>
> // `volume()` is a @MainActor async throwing method that throws
> // an `ArtboardError` if the request fails.
> do {
> let volume = try await artboard.volume()
> print("Current volume: \(volume)")
> } catch let error as ArtboardError {
> print("Failed to read volume: \(error)")
> }
> ```
> [tab] Legacy Runtime
>
> ```swift theme={null}
> // Set the current artboard's volume to 50%
> let viewModel = RiveViewModel(fileName: "my_rive_file")
> viewModel.riveModel?.volume = 0.5
> ```
# Resource Usage
Source: https://rive.app/docs/runtimes/apple/resource-usage
This page outlines some additional considerations when comparing Rive to other libraries' resource usage (specifically CPU and memory).
An important note is that Rive uses Metal APIs directly over other APIs and frameworks (like Core Animation) to be able to adjust its usage for best performance with Rive.
To get an accurate representation of the overall CPU and memory used by Rive, consider using the "Activity Monitor" template in Xcode, in addition to other templates.
Since Rive uses Metal directly, CPU usage and memory allocations appear in the app process. Other APIs can make use of other system processes, the stats of which will not be immediately visible by Xcode or Instruments.
## Core Animation
> [!NOTE]
>
> Lottie is an example of a library that uses Core Animation.
For libraries using Core Animation, logic and rendering is managed in a separate process known as the "Render Server" (`backboardd`). In doing so, CPU and memory usage isn't reported by the app process itself, and instead is reported by `backboardd`, which Xcode and Instruments are not monitoring by default.
By default, Xcode and Instruments show stats for the single process it is monitoring (and attached to). This is commonly the app that you are developing, unless otherwise specified. Resource usage for libraries using Core Animation will additionally appear in the "Render Server" process `backboardd`, and not just the app process.
The **overall** difference in resource usage can be found when profiling your app process *in addition to* the `backboardd` process. This can be seen by using the “Activity Monitor” Instruments template, and filtering by your app and the `backboardd` processes.
# Semantics
Source: https://rive.app/docs/runtimes/apple/semantics
Make your Rive views accessible to VoiceOver by enabling semantics in the Apple runtime.
This page covers enabling [semantics](/docs/editor/accessibility/semantics) in the New Runtime so your Rive views are accessible to VoiceOver. To learn what semantics are and how to add them to a graphic, see the [Semantics](/docs/editor/accessibility/semantics) editor documentation.
## Overview
In the Rive Editor, you can add semantic meaning to certain elements of your graphic-roles such as button, checkbox, tab, image, list, dialog, and more. Alongside these roles, you can add associated labels, values, states, and actions. These settings vary per role.
At runtime, the New Runtime reads those semantics from the running state machine and exposes them to [VoiceOver](https://support.apple.com/guide/iphone/turn-on-and-practice-voiceover-iph3e2e415f/ios) as the view's `accessibilityElements`, keeping them up to date as the state machine advances.
> [!WARNING]
>
> Semantics are **opt‑in**. The default mode is `.off`, so no accessibility elements are created until you enable semantics on the view.
> [!NOTE]
>
> Semantics must be defined in the editor to have any effect. If an element has no semantics, it is not exposed to screen readers, regardless of the mode you set. See [Feature Support](/docs/feature-support) for which runtimes currently support semantics.
## Availability
Semantics are available in the New Runtime only (not the Legacy Runtime), on every Apple platform the runtime supports except macOS (AppKit):
| Platform | Supported |
| - | - |
| iOS / iPadOS | ✅ |
| tvOS | ✅ |
| visionOS | ✅ |
| Mac Catalyst | ✅ |
| macOS (AppKit) | ❌ |
## Semantics modes
Semantics are controlled by the `Semantics` enum, which sets the VoiceOver integration mode for a Rive view:
| Mode | Description |
| - | - |
| `.off` | **Default.** Accessibility semantics are disabled. No accessibility elements are created, regardless of VoiceOver state. |
| `.on` | Accessibility semantics are always active. Elements are created and kept up‑to‑date on every frame. |
| `.automatic` | Accessibility semantics activate and deactivate automatically based on whether VoiceOver is currently running. |
For most apps, prefer `.automatic` — it keeps the accessibility tree in sync only while VoiceOver is active, avoiding unnecessary work when it isn't.
## Usage
Set the semantics mode on the view (UIKit) or with the `.semantics(_:)` modifier (SwiftUI).
```swift UIKit theme={null}
let rive = try await Rive(...)
let riveView = RiveUIView(rive: rive)
// Enable semantics only while VoiceOver is running
riveView.semantics = .automatic
// Always keep semantics active
riveView.semantics = .on
// Disable semantics (default)
riveView.semantics = .off
```
```swift SwiftUI theme={null}
var body: some View {
RiveUIViewRepresentable(rive: rive)
.semantics(.automatic)
// or .semantics(.on)
// or .semantics(.off)
}
```
```swift SwiftUI (Async) theme={null}
var body: some View {
AsyncRiveUIViewRepresentable {
let worker = try await Worker()
let file = try await File(source: ..., worker: worker)
let rive = try await Rive(file: file)
return rive
}
.semantics(.automatic)
}
```
# State Machine Playback
Source: https://rive.app/docs/runtimes/apple/state-machines
Playing a state machine
For more information on designing and building state machines in the Rive editor, please refer to [State Machine Overview](/docs/editor/state-machine).
A Rive state machine is a set of animation states and the transitions between them. At runtime there is limited ability to observe or modify the state directly. This is by design, as this would limit the ability of a designer in Rive to modify the state machine without creating breaking changes. Instead, state machines are indirectly controlled through transitions conditioned on [Data Binding](data-binding) properties.
A designer assigns a default state machine for each artboard in the Rive editor. They may create multiple state machines, each representing a different configuration of states and transitions. When rendering a Rive file and artboard, you may choose which state machine to play. If no state machine is specified, the default state machine for that artboard is used.
## Controlling playback
State machines play by "advancing" over time. This is done once per frame by the amount of time between frames. For example, for a graphic running at 60 frames per second, the state machine would be advanced by approximately 16.67 milliseconds (1/60th of a second) each frame. This advancing evaluates keyframes, transitions, data bindings changes, and ultimately the visible artboard elements to create the illusion of motion over time.
This runtime provides a way to control whether the state machine is playing. When paused or stopped, the state machine does not advance and the last rendered frame remains visible. When playing from pause, the state machine resumes from where it left off, whereas when playing from stop, it restarts from the entry state.
In addition to the paused/stopped state, state machines may also "settle". This is an optimization where the Rive runtime detects that no further changes will occur (for example, if there are no active transitions or animations). While settled the state machine will also stop advancing. This improves performance and energy use by avoiding unnecessary calculations. State machines are unsettled by external actions that change their state, such as user input or data binding changes. You can additionally force a state machine to unsettle by calling play, though it may immediately re-settle if there is no further work to be done.
## Playing State Machines
> [tab] New Runtime
>
> By default, the state machine of a `Rive` object will automatically play when in use by a `RiveUIView`.
>
> The following sections assumes that you have read through the [Getting an Artboard](/docs/runtimes/apple/artboards#getting-an-artboard) overview.
>
> ### Getting a State Machine
>
> Once you have created a `File` and `Artboard`, you can then retrieve information for and create `StateMachine` types.
>
> ```swift theme={null}
> // Get all state machine names
> let stateMachineNames = try await artboard.getStateMachineNames()
> // Get the default state machine for the artboard
> let defaultStateMachine = try await artboard.createStateMachine()
> // Get a state machine by name from the artboard
> let stateMachineByName = try await artboard.createStateMachine("StateMachine")
> ```
>
> Note that these are all async throwing functions marked as `@MainActor`. State machine creation also binds authored main and global view model defaults when available. Binding can throw `StateMachineError`; artboard lookup failures throw `ArtboardError`. To supply instances you retain, use `createStateMachine("StateMachine", binding: instance)` and the optional globals builder described in [Data Binding](/docs/runtimes/apple/data-binding#global-view-models).
>
> An example of when one of these functions will throw is if you call `.createStateMachine(_:)` with a name that is not in the origin `Artboard`, which will throw a `ArtboardError.invalidStateMachine(String)`.
>
> ### Using a State Machine
>
> Remember that the Rive configuration for a view is the `Rive` type. In the overview, we show initializing a `Rive` object with just a file. However, you can initialize a `Rive` object with a specific state machine:
>
> ```swift theme={null}
> let worker = try await Worker()
> let file = try await File(source: .local("my_file", Bundle.main), worker: worker)
> let artboardByName = try await file.createArtboard("Artboard")
> let stateMachine = try await artboardByName.createStateMachine("StateMachine")
> let rive = try await Rive(file: file, artboard: artboardByName, stateMachine: stateMachine)
> ```
> [tab] Legacy Runtime
>
> #### Autoplay the State Machine
>
> By default, RiveViewModel will automatically play the given state machine.
>
> ### SwiftUI
>
> ```swift theme={null}
> var stateChanger = RiveViewModel(
> fileName: "skills",
> stateMachineName: "Designer's Test",
> artboardName: "Banana"
> )
> ```
>
> ### UIKit
>
> ```swift theme={null}
> class StateMachineViewController: UIViewController {
> var viewModel = RiveViewModel(
> fileName: "skills",
> stateMachineName: "Designer's Test",
> artboardName: "Banana"
> )
>
> override public func loadView() {
> super.loadView()
>
> guard let stateMachineView = view as? StateMachineView else {
> fatalError("Could not find StateMachineView")
> }
>
> viewModel.setView(stateMachineView.riveView)
> }
> }
> ```
>
> ### Play
>
> If you set autoplay to false you can simply play the active animation or state machine.
>
> ```swift theme={null}
> simpleVM.play()
> ```
>
> ### Pause/Stop/Reset
>
> Based on certain events in your app you may want to adjust the playback further.
>
> ```swift theme={null}
> simpleVM.pause()
> simpleVM.stop()
> simpleVM.reset()
> ```
# Choosing a Renderer
Source: https://rive.app/docs/runtimes/choose-a-renderer/overview
Choose and configure the renderer used by Rive runtimes.
Rive runtimes can render through the [Rive Renderer](https://rive.app/renderer?utm_source=docs\&utm_medium=content) or, in some runtimes, a platform-specific renderer such as Canvas2D, Skia, or Impeller.
The Rive Renderer is designed to provide better performance and visual fidelity across all platforms. It leverages modern graphics APIs and techniques to deliver high-quality rendering for Rive graphics.
> [!NOTE]
>
> Some Rive features, including Vector Feathering, require the Rive Renderer.
>
> See [Feature
> Support](/docs/feature-support) for more information.
## Renderer defaults
| Runtime | Default Renderer | Options |
| - | - | - |
| [Web (JS)](#web-js) | Depends on package | Rive / Canvas2D |
| [Web (React)](#web-react) | Depends on package | Rive / Canvas2D |
| [Apple](#apple) | Rive | Rive |
| [Android (Compose)](#android-compose) | Rive | Rive |
| [Android (Legacy)](#android-legacy) | Rive | Rive / Canvas / Skia (removed as of v10.0.0) |
| [React Native](#react-native) | Rive | Rive |
| [Flutter](#flutter) | No default | Rive / Flutter Skia / Flutter Impeller |
## Runtime setup
Only some runtimes require you to choose or configure a renderer. The sections below cover runtimes that expose renderer setup through packages, initialization options, or factory settings.
If a runtime is not listed here, there is no renderer setup to configure. It uses the renderer supported by that runtime automatically.
> [tab] Web (JS)
>
> The Web runtime provides multiple packages with the same core API. Choose the package based on the renderer you want to use.
>
> | Package | Renderer | Use when |
> | - | - | - |
> | `@rive-app/webgl2` | Rive | You want the best support for Rive Renderer features (including GPU Canvas) and rendering fidelity. |
> | `@rive-app/canvas` | Canvas2D | You have several Rive instances on screen, want a slightly smaller package, or do not need Rive Renderer-only features. |
> | `@rive-app/canvas-lite` | Canvas2D | You want the smallest Canvas2D package and do not need the full Canvas2D runtime feature set. |
> [tab] Web (React)
>
> The Web runtime provides multiple packages with the same core API. Choose the package based on the renderer you want to use.
>
> | Package | Renderer | Use when |
> | - | - | - |
> | `@rive-app/react-webgl2` | Rive Renderer | You want the best support for Rive Renderer features (including GPU Canvas) and rendering fidelity. |
> | `@rive-app/react-canvas` | Canvas2D | You have several Rive instances on screen, want a slightly smaller package, or do not need Rive Renderer-only features. |
> | `@rive-app/react-canvas-lite` | Canvas2D | You want the smallest Canvas2D package and do not need the full Canvas2D runtime feature set. |
>
> > [!NOTE]
> >
> > These packages provide the Rive React component and hooks. If you want to use the imperative JavaScript runtime in a React app, install one of the Web JavaScript packages instead, such as `@rive-app/webgl2`, `@rive-app/canvas`, or `@rive-app/canvas-lite`.
> [tab] Apple
>
> The Apple runtime uses the Rive Renderer. In the Swift Concurrency API, you can opt a worker into [GPU Canvas](/docs/runtimes/apple/gpu-canvas) when it is created:
>
> ```swift theme={null}
> let worker = try await Worker(
> configuration: .init(enableGPUCanvas: true)
> )
> ```
>
> GPU Canvas is required for 3D content. The setting applies to every `File` loaded by that worker and every `Rive` object created from those files. It cannot be changed during the worker's lifetime.
> [tab] Android (Compose)
>
> The Compose API uses the Rive Renderer. You can opt a Rive worker into [GPU Canvas](/docs/runtimes/android/gpu-canvas) when it is created:
>
> ```kotlin theme={null}
> setContent {
> @OptIn(ExperimentalDeferredRendering::class)
> val riveWorker = rememberDeferredRiveWorker()
> }
> ```
>
> GPU Canvas is required for 3D and shader content. The setting applies to every file loaded with that worker. It cannot be changed during the worker's lifetime.
> [tab] Android (Legacy)
>
> Options: `Canvas / Skia (removed in v10.0.0)`
>
> Specify the renderer target in XML:
>
> ```kotlin theme={null}
> app:riveRenderer="Rive"
> … />
> ```
>
> Alternatively, when initializing Rive:
>
> ```kotlin theme={null}
> Rive.init(applicationContext, defaultRenderer = RendererType.Rive)
> ```
> [tab] React Native
>
> `@rive-app/react-native` uses the Rive Renderer. In `0.5.3` and later on iOS and `0.5.7` and later on Android, you can opt into [GPU Canvas](/docs/runtimes/react-native/gpu-canvas), which is required for 3D content:
>
> ```ts theme={null}
> import { RiveRuntime } from '@rive-app/react-native';
>
> RiveRuntime.setGPUCanvasEnabled(true);
> ```
>
> On Android, the Rive Renderer uses OpenGL by default. In `0.5.0` and later, you can opt into Vulkan:
>
> ```ts theme={null}
> RiveRuntime.setAndroidRenderBackend('vulkan');
> ```
>
> Vulkan requires Android 10 (API 29) or later. The runtime falls back to OpenGL when Vulkan is unavailable or fails to initialize. The call has no effect on iOS.
>
> Both settings apply to every Rive file in the app and must be made before the first Rive file is loaded. Calls made after that are ignored and log a warning.
> [tab] Flutter
>
> The Rive Renderer is available in the Flutter runtime as of `0.14.0`. Use the latest version (**0.14.11**) of the `rive` package for the newest fixes and improvements.
>
> The Rive Renderer is exposed through `rive_native`, which is included as a dependency of the `rive` package. See [Rive Native](/docs/runtimes/flutter/rive-native) for more information.
>
> When creating a Rive `File` or `FileLoader`, you need to specify a factory to use:
>
> * `Factory.rive` for the Rive renderer
> * `Factory.flutter` for the Flutter renderer (Skia or Impeller)
>
> ```dart theme={null}
> // Rive renderer
> File.asset("assets/vehicles.riv", riveFactory: Factory.rive)
> // Flutter renderer
> File.asset("assets/vehicles.riv", riveFactory: Factory.flutter)
> ```
>
> You can use different renderers for different graphics in your app.
>
> From `rive` `0.15.0`, `RiveNative.init()` tells you when the Rive Renderer cannot initialize, so you can handle it, for example by falling back to `Factory.flutter`. See [Initializing Rive](/docs/runtimes/flutter/flutter#initializing-rive).
>
> Some considerations when choosing a renderer:
>
> * If you plan on showing many Rive graphics that are all drawing to different Rive widgets consider using a [RivePanel](/docs/runtimes/flutter/flutter#rivepanel) with `Factory.rive` to draw multiple graphics to the same texture to reduce the overhead of allocating native render targets and textures. Or make use of `Factory.flutter`.
> * If you are showing a complex graphic, consider using `Factory.rive` to take advantage of the Rive renderer's optimizations.
> * Vector Feathering is only available with `Factory.rive`, so if you need that feature, use the Rive renderer.
# Angular
Source: https://rive.app/docs/runtimes/community-runtimes/angular
A community-maintained Angular wrapper runtime for Rive.
> [!NOTE]
>
> This is not a Rive owned or maintained project.
See the [GitHub repository](https://github.com/Grandgular/rive) for additional information.
# C# (UWP)
Source: https://rive.app/docs/runtimes/community-runtimes/c-sharp
A community-maintained C# (UWP) runtime for Rive.
> [!NOTE]
>
> This is not a Rive owned or maintained project.
This runtime is an experimental package in Windows Community Toolkit Labs. Its API may change between releases.
See the [GitHub repository](https://github.com/CommunityToolkit/Labs-Windows/blob/main/components/RivePlayer/samples/RivePlayer.md) for additional information.
# Qt / QtQuick
Source: https://rive.app/docs/runtimes/community-runtimes/qt-quick
A community-maintained Qt Quick runtime that draws Rive graphics in QML with the Rive Renderer.
> [!NOTE]
>
> This is not a Rive owned or maintained project.
rive-qt-plugin adds a `RiveView` item to QML. It draws with the Rive Renderer, using the same graphics API as the Qt window: Metal, Direct3D 11 or 12, OpenGL, or Vulkan. It requires Qt 6.5 or later and runs on macOS, Windows, and Linux.
* [Documentation](https://hypernuclear.com/docs/rive-qt/)
* [Getting started](https://hypernuclear.com/docs/rive-qt/getting-started/)
* [Viewer](https://hypernuclear.com/docs/rive-qt/viewer/)
* [QML API reference](https://hypernuclear.com/docs/rive-qt/qml-api/)
* [GitHub repository](https://github.com/hypernuclear/rive-qt-plugin)
# RiveCMP
Source: https://rive.app/docs/runtimes/community-runtimes/rive-cmp
A community-maintained Compose Multiplatform wrapper library for integrating Rive animations.
> [!NOTE]
>
> This is not a Rive owned or maintained project.
This library provides a unified API to use rive-android, rive-ios, and @rive-app/canvas across Android, iOS, and Web platforms in Compose Multiplatform.
See the [GitHub repository](https://github.com/muazkadan/Rive-CMP) for additional information.
# Asset Loading
Source: https://rive.app/docs/runtimes/cpp/asset-loading
Resolve out-of-band images, fonts, and audio.
A `.riv` file can either embed asset bytes (images, fonts, audio, scripts) **in-band**
or reference them by CDN UUID and let the runtime fetch them. Implement
`FileAssetLoader` to control the second path — resolving from disk, the
network, or your own asset pipeline.
## The `FileAssetLoader` interface
```cpp theme={null}
#include "rive/file_asset_loader.hpp"
#include "rive/assets/file_asset.hpp"
class FileAssetLoader : public RefCnt {
public:
virtual bool loadContents(FileAsset& asset,
Span inBandBytes,
Factory* factory) = 0;
};
```
`loadContents` is called once per asset during `File::import`. You return:
* `true` — you handled it. Either you populated `asset` synchronously, or
you kicked off async work and will populate it later.
* `false` — fall back to the in-band bytes (if any).
`asset` arrives typed: cast it to the concrete subclass to populate it.
| Asset type | Class | How to populate |
| - | - | - |
| Image | `ImageAsset` | `asset.renderImage(factory->decodeImage(bytes))` |
| Font | `FontAsset` | `asset.font(factory->decodeFont(bytes))` |
| Audio | `AudioAsset` | `asset.audioSource(factory->decodeAudio(bytes))` |
## Sync example: load by file name
```cpp theme={null}
#include "rive/file_asset_loader.hpp"
#include "rive/assets/image_asset.hpp"
#include "rive/assets/font_asset.hpp"
#include "rive/assets/audio_asset.hpp"
#include
#include
#include
#include
class DiskAssetLoader : public rive::FileAssetLoader {
public:
explicit DiskAssetLoader(std::filesystem::path root)
: m_root(std::move(root)) {}
bool loadContents(rive::FileAsset& asset,
rive::Span inBandBytes,
rive::Factory* factory) override
{
// Prefer in-band bytes when present.
if (inBandBytes.size() > 0) return false;
auto path = m_root / asset.uniqueFilename();
std::ifstream f(path, std::ios::binary);
if (!f) return false;
std::vector bytes((std::istreambuf_iterator(f)), {});
rive::Span span{bytes.data(), bytes.size()};
if (auto* img = dynamic_cast(&asset)) {
img->renderImage(factory->decodeImage(span));
return true;
}
if (auto* fnt = dynamic_cast(&asset)) {
fnt->font(factory->decodeFont(span));
return true;
}
if (auto* aud = dynamic_cast(&asset)) {
aud->audioSource(factory->decodeAudio(span));
return true;
}
return false;
}
private:
std::filesystem::path m_root;
};
```
`asset.uniqueFilename()` is the editor-assigned name with extension; use
`asset.cdnUuidStr()` if you index by CDN UUID instead.
## Wiring it up
```cpp theme={null}
rcp loader = make_rcp("assets/");
ImportResult result;
rcp file = File::import(bytes, factory, &result, loader);
```
The loader is reference-counted — `File` keeps it alive for the file's
lifetime so async loads can complete after `import` returns.
## Async loading
For async (HTTP, decoder thread, etc), return `true` from `loadContents`
**without** calling `renderImage` / `font` / `audioSource`, then populate the
asset later from any thread:
```cpp theme={null}
bool loadContents(FileAsset& asset, Span, Factory* factory) override {
auto* image = dynamic_cast(&asset);
if (!image) return false;
rcp keepAlive = ref_rcp(image);
fetchAsync(image->cdnUuidStr(), [keepAlive, factory](std::vector bytes) {
// Assumes this callback is dispatched to the render thread — see the
// warning below about decoder thread-safety.
rcp ri =
factory->decodeImage({bytes.data(), bytes.size()});
keepAlive->renderImage(std::move(ri));
// The next advanceAndApply will pick up the new image.
});
return true;
}
```
> [!WARNING]
>
> Decoders (`Factory::decodeImage`, `Factory::decodeFont`,
> `Factory::decodeAudio`) are **not guaranteed thread-safe** for every
> backend. If you decode off-thread, decode into a CPU-side representation
> and finalize the GPU upload back on the render thread, or use a
> thread-safe `Factory` if your backend supports it.
## Built-in loaders
For simple cases the runtime ships a relative-path loader you can extend:
```cpp theme={null}
#include "rive/relative_local_asset_loader.hpp"
rcp loader =
make_rcp("/path/to/assets");
```
It loads files by `uniqueFilename()` from a directory on disk — handy for
samples and tooling.
## When in-band bytes already cover everything
If your `.riv` file embeds all of its assets, you can skip the loader
entirely. `inBandBytes` will be non-empty for those assets and the runtime
will decode them with the `Factory` you provided.
# Command Queue
Source: https://rive.app/docs/runtimes/cpp/command-queue
Drive the C++ runtime from a separate thread via CommandQueue and CommandServer.
`CommandQueue` is an asynchronous, thread-safe alternative to the direct
`File` / `Artboard` / `StateMachineInstance` API documented elsewhere. Your
application thread enqueues commands (load a file, advance a state machine,
forward a pointer event) and a `CommandServer` worker drains them on the
render thread.
Use it when:
* Your app and render threads are separate, and you don't want to
cross-thread-call into the direct API.
* You want a Rive-content thread that's decoupled from the GPU thread.
* You need a stable handle-based identity for `File` / `Artboard` /
`StateMachineInstance` objects across thread boundaries.
If your render loop and your app logic are already on the same thread,
prefer the direct API — `CommandQueue` adds indirection and listener
plumbing you don't need.
## Architecture

* `CommandQueue` is **reference-counted** (`rcp`) and
thread-safe. The app thread keeps one; the server holds the other end.
* `CommandServer` owns the real `File`, `ArtboardInstance`, and
`StateMachineInstance` objects. They never escape the render thread.
* All cross-thread identifiers are typed **handles**:
`FileHandle`, `ArtboardHandle`, `StateMachineHandle`,
`ViewModelInstanceHandle`, `RenderImageHandle`, `FontHandle`,
`AudioSourceHandle`. The app thread holds handles; the server resolves
them to real objects.
* Async results (file loaded, state machine settled, image decoded) come
back via **listener callbacks** registered against handles.
## Setting up the queue and server
```cpp theme={null}
#include "rive/command_queue.hpp"
#include "rive/command_server.hpp"
// Shared between threads.
rcp queue = make_rcp();
```
On the render thread, create a `CommandServer` and pump it:
```cpp theme={null}
// `factory` is your Factory* — usually your RenderContext.
CommandServer server(queue, factory);
// Drain pending commands once per frame...
server.processCommands();
// ...or block on a dedicated thread until disconnect.
// server.serveUntilDisconnect();
```
`processCommands()` is non-blocking — call it before each frame.
`serveUntilDisconnect()` is the run-loop variant for a worker thread:
blocks waiting for commands, and returns when the app thread calls
`queue->disconnect()`.
## Loading a file and creating a State Machine
All these calls happen on the app thread. They enqueue commands and
return handles **immediately** — the actual work happens on the server
thread.
```cpp theme={null}
std::vector rivBytes = readFile("hero.riv");
FileHandle file = queue->loadFile(std::move(rivBytes));
ArtboardHandle artboard = queue->instantiateDefaultArtboard(file);
StateMachineHandle sm = queue->instantiateDefaultStateMachine(artboard);
```
The handles are valid to use immediately even though the load hasn't
happened yet — subsequent commands queued against them will execute in
order on the server.
## Advancing and drawing
```cpp theme={null}
// App thread:
queue->advanceStateMachine(sm, /* dt = */ 1.f / 60.f);
```
Drawing is handled differently — you register a draw callback that runs
on the server thread when the queue tells it to. Pattern: create a
**draw key**, attach a callback, then tell the server to run that key.
See the `CommandQueue::drawCallback` and `runDraw` methods in
[`command_queue.hpp`](https://github.com/rive-app/rive-runtime/blob/main/include/rive/command_queue.hpp)
for the full draw-callback API; the canonical example is the
command-queue D3D11 sample in the rive monorepo
(`packages/sample_win32_d3d11_cq/`).
## Async results: listeners
Because commands run asynchronously, results come back via listener
callbacks. Each handle type has a matching listener with `on…` methods:
```cpp theme={null}
class MyFileListener : public CommandQueue::FileListener
{
public:
void onFileLoaded(const FileHandle, uint64_t requestId) override
{
// Safe to instantiate artboards now, etc.
}
};
MyFileListener listener;
listener.attach(queue, file); // register against this handle
```
Listeners available include:
* `FileListener` — `onFileLoaded`, `onFileDeleted`, `onArtboardsListed`,
`onViewModelsListed`, …
* `ArtboardListener` — `onArtboardInstanced`, `onArtboardError`,
`onArtboardDeleted`.
* `StateMachineListener` — `onStateMachineInstanced`,
`onStateMachineSettled` (called on the request that caused the state
machine to settle), …
* `ViewModelInstanceListener`, `RenderImageListener`, `FontListener`,
`AudioSourceListener` — for the other resource types.
`requestId` lets you correlate callbacks with specific commands.
Pass a non-zero `requestId` to the queue methods that accept one (e.g.
`deleteFile(handle, requestId)`) and your listener will receive the same
ID back.
## Pointer events
Pointer events go through the queue too. `CommandQueue::PointerEvent`
carries the screen-space position; the server converts it to artboard
space using the state machine's most recent transform:
```cpp theme={null}
CommandQueue::PointerEvent ev;
ev.position = { mouseX, mouseY };
ev.kind = CommandQueue::PointerEvent::Kind::move;
queue->queuePointerEvent(sm, ev);
```
## Teardown
The app thread tells the server to stop:
```cpp theme={null}
queue->disconnect();
```
If the server is running `serveUntilDisconnect()`, that call returns
when the disconnect command arrives. After that, joining the server
thread is your responsibility.
Resource handles are cleaned up by enqueuing explicit delete commands
(or letting the server destructor reap them):
```cpp theme={null}
queue->deleteStateMachine(sm);
queue->deleteArtboard(artboard);
queue->deleteFile(file);
```
## When to use the direct API instead
The direct `File` / `Artboard` / `StateMachineInstance` API documented in
the other pages on this site is simpler when:
* Your app already drives Rive from the render thread.
* You don't need handle-based identity across threads.
* You want synchronous return values rather than listener callbacks.
`CommandQueue` exists for the multithreaded case — it's the right tool
for engines, render servers, and apps with a dedicated GPU thread.
# Data Binding
Source: https://rive.app/docs/runtimes/cpp/data-binding
Drive Rive ViewModels from C++.
Rive's **View Models** expose strongly-typed properties
(numbers, strings, colors, booleans, enums, triggers, lists, nested view
models, image and artboard references) that an artboard binds to. From C++
you instance a view model, mutate properties, and the bound visuals update
on the next `advanceAndApply`.
## Concepts
* `ViewModelRuntime` — schema for a view model defined in the editor. Lives
in the `File`.
* `ViewModelInstanceRuntime` — typed wrapper around an instance of that
schema. Exposes the property API (`propertyNumber`, `propertyString`, etc).
You own it via `rcp<>`.
* `ViewModelInstance` — the underlying bindable instance. `Artboard` and
`StateMachineInstance` bind to this type. Get one from a
`ViewModelInstanceRuntime` with `.instance()`.
* `ViewModelInstance*Runtime` — typed handles for individual properties
(`…NumberRuntime`, `…StringRuntime`, etc).
## Creating an instance
The simplest path is to ask the file for the artboard's default view model,
then create a default instance from it:
```cpp theme={null}
#include "rive/file.hpp"
#include "rive/viewmodel/runtime/viewmodel_runtime.hpp"
ViewModelRuntime* vm = file->defaultArtboardViewModel(artboard.get());
if (!vm) return; // artboard has no default view model
rcp instance = vm->createDefaultInstance();
if (instance) {
artboard->bindViewModelInstance(instance->instance());
sm ->bindViewModelInstance(instance->instance());
}
```
For full control, look up a specific view model schema by index or name and
create instances from it:
```cpp theme={null}
ViewModelRuntime* vm = file->viewModelByName("Card");
if (!vm) return; // no view model with that name
size_t propCount = vm->propertyCount();
size_t instCount = vm->instanceCount();
rcp instance = vm->createDefaultInstance();
// alternatives — pick one and replace the line above:
// rcp instance = vm->createInstanceFromName("Hero");
// rcp instance = vm->createInstanceFromIndex(0);
// rcp instance = vm->createInstance(); // no editor preset; properties at type defaults
if (!instance) return;
artboard->bindViewModelInstance(instance->instance());
sm ->bindViewModelInstance(instance->instance());
```
> [!NOTE]
>
> Bind the same `ViewModelInstance` to **both** the artboard and the state machine.
> The artboard binding drives layout-affecting properties; the state-machine binding
> drives state-machine transitions and listener conditions.
## Reading & writing properties
All accessors are path-based — `/`-separated for nested view models.
```cpp theme={null}
auto* card = instance.get();
// Number
if (auto* score = card->propertyNumber("score")) {
score->value(42.0f);
float v = score->value();
}
// String
if (auto* title = card->propertyString("title")) {
title->value("Hello");
}
// Boolean
if (auto* on = card->propertyBoolean("isOpen")) {
on->value(true);
}
// Color (ARGB packed)
if (auto* col = card->propertyColor("accent")) {
col->value(0xFFE53935);
}
// Trigger (edge event)
if (auto* fire = card->propertyTrigger("fire")) {
fire->trigger();
}
// Enum (by string label)
if (auto* mood = card->propertyEnum("mood")) {
mood->value("happy");
}
```
### Nested View Models
```cpp theme={null}
// Option 1: deep path string.
auto* headerTitle = card->propertyString("header/title");
// Option 2: walk the tree.
rcp header = card->propertyViewModel("header");
auto* title = header->propertyString("title");
```
You can also **swap** a nested view model wholesale — useful for swapping a
list cell's data without rebuilding the artboard:
```cpp theme={null}
rcp newHeader = vm->createDefaultInstance();
card->replaceViewModel("header", newHeader.get());
```
### Lists
```cpp theme={null}
auto* items = card->propertyList("items");
// Append, insert, remove, replace, swap, count.
items->addInstance(rowInstance.get());
items->addInstanceAt(rowInstance.get(), 0);
items->removeInstanceAt(2);
items->swap(0, 1);
size_t n = items->size();
rcp row = items->instanceAt(0);
```
List items are themselves `ViewModelInstanceRuntime`s — same property API as
above.
### Image & Artboard properties
```cpp theme={null}
auto* image = card->propertyImage("avatar");
image->value(decodedRenderImage.get()); // RenderImage*
auto* artboardRef = card->propertyArtboard("badge");
artboardRef->value(file->bindableArtboardNamed("Badge")); // rcp
```
## Lifecycle
* A `ViewModelInstanceRuntime` is a thin wrapper over a `ViewModelInstance`.
Hold the `rcp<>` for as long as anything binds to it.
* Property handles (`ViewModelInstanceNumberRuntime*`, etc) are owned by
the parent instance. Cache the pointer — it stays valid for the
instance's lifetime.
* After mutating properties, the next `sm->advanceAndApply(dt)` propagates
the changes through data binds and into rendering.
## When properties don't exist
Every `propertyX(name)` getter returns `nullptr` if the name doesn't
resolve, so you can probe an instance safely:
```cpp theme={null}
if (auto* p = instance->propertyNumber("optional")) {
p->value(1.0f);
}
```
For introspection, walk the schema:
```cpp theme={null}
for (const PropertyData& p : instance->properties()) {
// p.name, p.type ∈ { number, string, boolean, color, enum, trigger,
// list, viewModel, image, artboard, ... }
}
```
# External Renderer
Source: https://rive.app/docs/runtimes/cpp/external-renderer
Plug Rive into your own GPU backend or 2D engine.
`RiveRenderer` and `rive::gpu::RenderContext` are one possible backend. The
core runtime is renderer-agnostic — anything you pass to
`StateMachineInstance::draw` only has to implement two interfaces:
* **`rive::Renderer`** — receives draw / clip / save / restore commands.
* **`rive::Factory`** — creates `RenderPath`, `RenderPaint`, `RenderImage`,
`RenderShader`, `RenderBuffer`, `Font`, `AudioSource` from raw bytes or
parameters during file import.
Implement both and Rive will route everything through them.
## Use cases
* You already have a 2D vector engine (Skia, Direct2D, custom) and want
Rive to render through it.
* You're targeting a platform Rive doesn't ship a backend for.
* You want CPU-side hit-testing or analytics — render into a no-op
`Renderer` that records command counts.
If you only need Rive on Windows / macOS / iOS / Linux / Web / Android,
prefer the [built-in renderers](/docs/runtimes/cpp/renderers) — they're
faster and feature-complete.
## The `Renderer` interface
```cpp theme={null}
class Renderer {
public:
virtual void save() = 0;
virtual void restore() = 0;
virtual void transform(const Mat2D&) = 0;
virtual void drawPath(RenderPath*, RenderPaint*) = 0;
virtual void clipPath(RenderPath*) = 0;
virtual void drawImage(const RenderImage*,
ImageSampler, BlendMode,
float opacity) = 0;
virtual void drawImageMesh(const RenderImage*, ImageSampler,
rcp verts_f32,
rcp uvs_f32,
rcp indices_u16,
uint32_t vertexCount,
uint32_t indexCount,
BlendMode, float opacity) = 0;
virtual void modulateOpacity(float opacity) = 0;
};
```
A few constraints worth knowing up front:
* `save` / `restore` form a stack and must capture: the current transform,
clip stack, and the modulated opacity.
* `clipPath` adds to the current clip — never replaces it.
* `modulateOpacity` is multiplicative; `0.5` then `0.2` ⇒ `0.1` effective
opacity until the next `restore`.
* `drawImageMesh` indices are 16-bit; vertex / UV buffers are
tightly-packed `float` pairs.
## The `Factory` interface
```cpp theme={null}
class Factory {
public:
virtual rcp makeRenderBuffer(
RenderBufferType, RenderBufferFlags, size_t sizeInBytes) = 0;
virtual rcp makeLinearGradient(
float sx, float sy, float ex, float ey,
const ColorInt colors[], const float stops[], size_t count) = 0;
virtual rcp makeRadialGradient(
float cx, float cy, float radius,
const ColorInt colors[], const float stops[], size_t count) = 0;
virtual rcp makeRenderPath(RawPath&, FillRule) = 0;
virtual rcp makeEmptyRenderPath() = 0;
virtual rcp makeRenderPaint() = 0;
virtual rcp decodeImage(Span) = 0;
rcp decodeFont (Span); // non-virtual helper
rcp decodeAudio(Span); // non-virtual helper
};
```
Things to keep in mind:
* Gradient `colors[]` are packed ARGB ints; `stops[]` are normalized 0..1.
* `makeRenderPath(RawPath&, FillRule)` may **steal** the path's storage —
treat the input as moved-from after the call.
* `decodeImage` is called with raw PNG / JPEG / WebP bytes, etc. Decode in
whatever pixel format your renderer prefers and wrap the result in a
subclass of `RenderImage`.
* `decodeFont` / `decodeAudio` are non-virtual helpers that fan out to
Rive's built-in HarfBuzz / miniaudio paths. They are not subclass
override points; use the actual virtual `Factory` extension points for
custom font shaping or audio integration.
## RenderPath / RenderPaint subclasses
Each holds the state your backend reads during drawing:
```cpp theme={null}
class MyPath : public RenderPath {
public:
void rewind() override { /* clear */ }
void moveTo(float x, float y) override { /* … */ }
void lineTo(float x, float y) override { /* … */ }
void cubicTo(float ox, float oy,
float ix, float iy,
float x, float y) override { /* … */ }
void close() override { /* … */ }
void addRenderPath(RenderPath*, const Mat2D&) override { /* … */ }
void addRawPath(const RawPath&) override { /* … */ }
};
class MyPaint : public RenderPaint {
public:
void style(RenderPaintStyle) override;
void color(unsigned int) override;
void thickness(float) override;
void join(StrokeJoin) override;
void cap(StrokeCap) override;
void blendMode(BlendMode) override;
void shader(rcp) override;
void invalidateStroke() override;
};
```
(Method signatures match `rive/command_path.hpp` (for `CommandPath`) and
`rive/renderer.hpp` (for `RenderPath` and `RenderPaint`) — read those for
the full set.)
## Wiring it up
```cpp theme={null}
class MyFactory : public rive::Factory { /* ... */ };
MyFactory factory;
rcp file = File::import(bytes, &factory);
auto artboard = file->artboardDefault();
auto sm = artboard->defaultStateMachine();
MyRenderer renderer;
sm->advanceAndApply(dt);
sm->draw(&renderer);
```
There's no `RenderContext` in this path — your `Renderer` is responsible
for making the GPU calls (or buffering them, or counting them, or whatever
you want).
## Reference implementations
All paths below are in the [rive-runtime](https://github.com/rive-app/rive-runtime) repo.
| Project | Uses | Where |
| - | - | - |
| `rive::gpu::RenderContext` | Pixel-local-storage GPU renderer | `renderer/src/` |
| `SkiaFactory` / `SkiaRenderer` | Skia | `skia/renderer/` |
| `CGFactory` / `CGRenderer` | CoreGraphics | `cg_renderer/` |
| `SokolFactory` | Sokol (tessellation) | `tess/src/sokol/` |
The Skia and CoreGraphics implementations are the most direct templates for
a "forward to an existing 2D engine" `Renderer`.
# File & Artboard
Source: https://rive.app/docs/runtimes/cpp/file-and-artboard
Importing .riv data and instancing artboards.
A Rive `.riv` file is a binary container of **artboards**, **animations**,
**state machines**, **view models**, and **assets**. The C++ API gives you
read-only access to that container (`File`, `Artboard`) and mutable instances
you can advance and draw (`ArtboardInstance`, `StateMachineInstance`).
## Importing a file
```cpp theme={null}
#include "rive/file.hpp"
ImportResult result;
rcp file = File::import(
Span{bytes.data(), bytes.size()},
factory, // a Factory* — usually your RenderContext
&result, // optional
assetLoader); // optional rcp
switch (result) {
case ImportResult::success: break;
case ImportResult::unsupportedVersion: /* runtime is older than file */ break;
case ImportResult::malformed: /* bad bytes */ break;
}
```
`File` is reference-counted (`rcp`). It owns the parsed object graph and
the assets imported in-band. Keep it alive for as long as any artboard
instance derived from it is alive.
> [!WARNING]
>
> The `Factory*` you pass in is responsible for constructing every
> `RenderPath`, `RenderPaint`, `RenderImage`, font, and audio source the
> file produces. When using Rive's GPU renderer, this is your
> `RenderContext`. When using a custom renderer, it is your `Factory`
> implementation.
## Determinism
```cpp theme={null}
File::deterministicMode = true;
```
A static flag that forces a fixed RNG seed and timestamp-driven scrolling for
all subsequent loads. Useful for golden-image tests and frame-by-frame
captures.
## Querying Artboards
```cpp theme={null}
size_t count = file->artboardCount();
std::string name = file->artboardNameAt(0);
Artboard* byName = file->artboard("Hero"); // by name
Artboard* byIndex = file->artboard(size_t{0}); // by index
Artboard* first = file->artboard(); // file's first artboard
```
`Artboard*` returned by these accessors is **read-only metadata** — do not
advance or draw it. To play an artboard, create an instance.
## Instancing
```cpp theme={null}
// Most common: copy of the file's default artboard.
std::unique_ptr ab = file->artboardDefault();
// Or by name / index:
auto namedAb = file->artboardNamed("Hero");
auto indexedAb = file->artboardAt(2);
```
Each call returns a **fresh, independent copy**. You can have many instances of
the same artboard playing at once — each with its own state machine, its own
data bindings, and its own layout.
```cpp theme={null}
size_t anims = ab->animationCount();
size_t states = ab->stateMachineCount();
std::string animName = ab->animationNameAt(0);
std::string smName = ab->stateMachineNameAt(0);
// Designer-marked default state machine, if any.
int defaultIdx = ab->defaultStateMachineIndex(); // -1 if none
```
## Creating a State Machine
`StateMachineInstance` is the unit of playback in C++ — what you advance
each frame, draw, and forward pointer events to.
```cpp theme={null}
#include "rive/animation/state_machine_instance.hpp"
std::unique_ptr sm = ab->defaultStateMachine();
if (!sm && ab->stateMachineCount() > 0) {
sm = ab->stateMachineAt(0);
}
```
## Sizing & Layout
Artboards have an intrinsic size set in the editor, plus an optional layout
mode (Yoga-driven). For non-layout fits the artboard stays at its intrinsic
size; for `Fit::layout` you drive width and height yourself:
```cpp theme={null}
#include "rive/layout.hpp"
if (fit == Fit::layout) {
ab->width(static_cast(windowWidth));
ab->height(static_cast(windowHeight));
} else {
ab->resetSize(); // back to intrinsic
}
// Re-evaluate layout before the next draw.
sm->advanceAndApply(0.f);
```
`Artboard::bounds()` returns the current 'rect' — feed it to `computeAlignment`
to map artboard-space into your viewport.
## File lifetime
Reference-counted ownership keeps lifetimes simple:
```cpp theme={null}
rcp file = File::import(...);
auto ab = file->artboardDefault(); // unique_ptr
auto sm = ab->defaultStateMachine(); // unique_ptr
// Tear down in reverse order:
sm.reset();
ab.reset();
file = nullptr; // last rcp drops the File
```
Always destroy Rive objects **before** tearing down your `RenderContext` —
they hold references to GPU resources owned by the context.
# Getting Started
Source: https://rive.app/docs/runtimes/cpp/getting-started
Build rive-cpp and render a .riv file.
This guide walks you through cloning the runtime, compiling it, and getting a
`.riv` file on screen with a real GPU backend.
## Prerequisites
* A recent **clang** or **MSVC** that supports C++17.
* **git** — the build script will clone and bootstrap `premake5` itself.
* Platform SDK for your renderer of choice (Windows SDK for D3D, Xcode for
Metal, Vulkan SDK for Vulkan, etc).
> [!NOTE]
>
> Rive uses clang [vector
> builtins](https://reviews.llvm.org/D111529). When building with clang, use the
> latest version available — older toolchains may fail to compile the renderer.
## 1. Clone and build the runtime
```bash theme={null}
git clone https://github.com/rive-app/rive-runtime.git
cd rive-runtime/renderer
```
The runtime ships a build helper at `build/build_rive.sh` (with a
PowerShell wrapper `build_rive.ps1` for Windows). It installs the pinned
`premake5` version on first run and dispatches to the right build system
for your platform (gmake2 on macOS/Linux, MSBuild on Windows, etc).
```bash macOS / Linux theme={null}
../build/build_rive.sh release
```
```powershell Windows theme={null}
..\build\build_rive.ps1 release
```
Common variants:
* `build_rive.sh` (no args) — debug build for the host.
* `build_rive.sh release clean` — clean rebuild.
* `build_rive.sh ninja release` — use Ninja instead of make.
* `build_rive.sh ios release` / `build_rive.sh android release` —
cross-compile.
Build artifacts land in `out/release/` (or `out/debug/`). You'll link
against `librive.a` (or `rive.lib` on Windows), plus the per-backend
renderer libraries like `librive_pls_renderer.a`.
## 2. Add headers to your project
The public include roots are:
```
rive-runtime/include # rive-cpp core
rive-runtime/renderer/include # GPU renderer (only if you use rive::gpu)
```
A minimal CMake snippet:
```cmake theme={null}
target_include_directories(my_app PRIVATE
${RIVE}/include
${RIVE}/renderer/include
)
target_link_libraries(my_app PRIVATE
rive
rive_pls_renderer
# plus your backend, e.g. d3d11, dxgi on Windows
)
```
## 3. Load a `.riv` file
```cpp theme={null}
#include "rive/file.hpp"
#include
#include
#include
using namespace rive;
std::vector readFile(const char* path) {
std::ifstream in(path, std::ios::binary);
return {std::istreambuf_iterator(in), {}};
}
// `factory` is a Factory* — usually your RenderContext (which inherits Factory).
auto bytes = readFile("hero.riv");
ImportResult result;
rcp file = File::import(bytes, factory, &result);
if (!file || result != ImportResult::success) {
// Bad file or unsupported version.
return;
}
```
## 4. Pick an Artboard and a State Machine
```cpp theme={null}
#include "rive/artboard.hpp"
#include "rive/animation/state_machine_instance.hpp"
std::unique_ptr artboard = file->artboardDefault();
std::unique_ptr sm = artboard->defaultStateMachine();
if (!sm && artboard->stateMachineCount() > 0) {
sm = artboard->stateMachineAt(0);
}
```
## 5. Advance and draw
A render loop has three phases each frame: **advance**, **draw**, **flush**.
```cpp theme={null}
#include "rive/renderer/rive_renderer.hpp"
#include "rive/renderer/render_context.hpp"
void renderFrame(float dt) {
sm->advanceAndApply(dt);
RenderContext::FrameDescriptor frame{};
frame.renderTargetWidth = windowWidth;
frame.renderTargetHeight = windowHeight;
frame.clearColor = 0xff202020; // ARGB
renderContext->beginFrame(frame);
RiveRenderer renderer(renderContext.get());
renderer.save();
renderer.align(Fit::contain,
Alignment::center,
AABB(0, 0, windowWidth, windowHeight),
artboard->bounds());
sm->draw(&renderer);
renderer.restore();
RenderContext::FlushResources flush{};
flush.renderTarget = renderTarget.get();
renderContext->flush(flush);
}
```
> [!TIP]
>
> Use a **fixed timestep** for `advanceAndApply` (e.g. 1/120s) and accumulate
> real elapsed time. State machines are deterministic at fixed steps, which
> makes playback reproducible across machines and frame rates. See
> [Rendering Loop](/docs/runtimes/cpp/rendering-loop).
## 6. Forward input
Route pointer events back through the state machine so
listeners and hit-testing work:
```cpp theme={null}
#include "rive/renderer.hpp"
Mat2D align = computeAlignment(Fit::contain,
Alignment::center,
AABB(0, 0, w, h),
artboard->bounds());
Vec2D toArtboard(int x, int y) {
return align.invertOrIdentity() * Vec2D{(float)x, (float)y};
}
sm->pointerMove(toArtboard(mouseX, mouseY));
sm->pointerDown(toArtboard(mouseX, mouseY));
sm->pointerUp(toArtboard(mouseX, mouseY));
```
## What's next
> [card] [Renderers](/docs/runtimes/cpp/renderers)
>
> Wire up your platform's GPU backend.
> [card] [State Machines](/docs/runtimes/cpp/state-machines)
>
> Advance state machines, forward pointer events, and react to state changes.
# C++ Runtime
Source: https://rive.app/docs/runtimes/cpp/overview
Load, advance, and render Rive content from C++.
The Rive C++ runtime (`rive-cpp`) is the lowest-level Rive runtime. It loads
`.riv` files, advances state machines and animations, and draws into any
`Renderer` — the
[Rive renderer](/docs/runtimes/cpp/renderers) (Metal, Vulkan, D3D11, D3D12,
OpenGL/WebGL) or [your own implementation](/docs/runtimes/cpp/external-renderer).
Higher level Rive runtimes (Apple, Android, Flutter, Unity, Unreal) wrap this
library.
Use the C++ runtime when you are:
* Embedding Rive in a C++ application or game engine.
* Targeting a platform that doesn't have a Rive runtime yet.
* Plugging Rive into your own renderer or render graph.
> [card] [Getting Started](/docs/runtimes/cpp/getting-started)
>
> Build the runtime and put a `.riv` file on screen in under 100 lines of code.
> [card] [Renderers](/docs/runtimes/cpp/renderers)
>
> Set up the GPU backend for your platform — D3D11, D3D12, Metal, Vulkan, or GL.
> [card] [File & Artboard](/docs/runtimes/cpp/file-and-artboard)
>
> Import `.riv` files, query artboards, and create `ArtboardInstance`s.
> [card] [State Machines](/docs/runtimes/cpp/state-machines)
>
> Advance scenes, forward pointer events, and react to state changes.
> [card] [Data Binding](/docs/runtimes/cpp/data-binding)
>
> Drive a Rive `ViewModel` from your application state.
> [card] [Asset Loading](/docs/runtimes/cpp/asset-loading)
>
> Resolve out-of-band images, fonts, and audio with `FileAssetLoader`.
> [card] [Rendering Loop](/docs/runtimes/cpp/rendering-loop)
>
> `beginFrame` / `flush` — what runs each frame and what it costs.
> [card] [External Renderer](/docs/runtimes/cpp/external-renderer)
>
> Implement `Renderer` and `Factory` to use your own GPU backend.
## Architecture at a glance

**`File` / `Artboard` / `StateMachineInstance` know nothing about the GPU**,
and `Renderer` / `RenderContext` know nothing about Rive content. Either
half works on its own — render Rive content through your own `Renderer`
implementation, or drive `RiveRenderer` with non-Rive draw commands.
## Supported platforms & APIs
| Backend | Headers | Class |
| - | - | - |
| D3D11 | `rive/renderer/d3d11/render_context_d3d_impl.hpp` | `RenderContextD3DImpl` |
| D3D12 | `rive/renderer/d3d12/render_context_d3d12_impl.hpp` | `RenderContextD3D12Impl` |
| Metal | `rive/renderer/metal/render_context_metal_impl.h` | `RenderContextMetalImpl` |
| Vulkan | `rive/renderer/vulkan/render_context_vulkan_impl.hpp` | `RenderContextVulkanImpl` |
| OpenGL / WebGL | `rive/renderer/gl/render_context_gl_impl.hpp` | `RenderContextGLImpl` |
> [!NOTE]
>
> The C++ runtime is also the foundation for Rive's [iOS/macOS](/docs/runtimes/apple),
> [Android](/docs/runtimes/android), and [Flutter](/docs/runtimes/flutter) runtimes — those
> platforms ship a thin wrapper, not a separate engine.
## Source & license
* GitHub: [rive-app/rive-runtime](https://github.com/rive-app/rive-runtime)
* License: MIT
* Build system: [premake5](https://premake.github.io/)
# Renderers
Source: https://rive.app/docs/runtimes/cpp/renderers
Set up the GPU backend for your platform.
`rive::gpu::RenderContext` is the API-agnostic frontend to Rive's GPU
renderer. You create one of the per-backend `*Impl::MakeContext` factories,
hand it to your render loop, and the rest of the C++ API stays identical.

`RenderContext` also implements `rive::Factory`, so the same object you pass to
`File::import` is the one that owns your GPU resources.
> [tab] D3D11
>
> Header: `rive/renderer/d3d11/render_context_d3d_impl.hpp`
>
> ```cpp theme={null}
> #include "rive/renderer/d3d11/render_context_d3d_impl.hpp"
>
> using namespace rive::gpu;
>
> ComPtr device;
> ComPtr context;
> // ... create device + context with D3D_FEATURE_LEVEL_11_1 ...
>
> D3DContextOptions options;
> options.isIntel = adapterDesc.VendorId == 0x163C ||
> adapterDesc.VendorId == 0x8086 ||
> adapterDesc.VendorId == 0x8087;
>
> std::unique_ptr rc =
> RenderContextD3DImpl::MakeContext(device, context, options);
>
> auto* impl = rc->static_impl_cast();
> rcp target = impl->makeRenderTarget(width, height);
>
> // Each frame: bind the current backbuffer to the render target.
> target->setTargetTexture(backbufferTexture);
> ```
>
> Swap-chain notes:
>
> * Set `BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_UNORDERED_ACCESS`.
> * Use `DXGI_FORMAT_R8G8B8A8_UNORM` (or the `_SRGB` variant); other formats
> may force the renderer onto an offscreen path.
> * Set `options.isIntel = true` on Intel HD Graphics — works around a driver
> bug in pixel-local-storage emulation.
>
> For a working reference, see Rive's
> [`tests/player`](https://github.com/rive-app/rive-runtime/tree/main/tests/player)
> sample app and the D3D-specific wiring in
> [`tests/common/offscreen_rendertarget_d3d.cpp`](https://github.com/rive-app/rive-runtime/blob/main/tests/common/offscreen_rendertarget_d3d.cpp).
> [tab] D3D12
>
> Header: `rive/renderer/d3d12/render_context_d3d12_impl.hpp`
>
> ```cpp theme={null}
> #include "rive/renderer/d3d12/render_context_d3d12_impl.hpp"
>
> using namespace rive::gpu;
>
> ComPtr device;
> ComPtr initList; // recording state
>
> D3DContextOptions options;
> std::unique_ptr rc =
> RenderContextD3D12Impl::MakeContext(device, initList.Get(), options);
>
> auto* impl = rc->static_impl_cast();
> rcp target = impl->makeRenderTarget(width, height);
> ```
>
> Each frame, populate `RenderContext::FlushResources::externalCommandBuffer`
> with the `ID3D12GraphicsCommandList` that should record Rive's draws, and
> bump `currentFrameNumber` / `safeFrameNumber` so the renderer can recycle
> buffers safely against your fence values.
>
> > [!WARNING]
> >
> > The init command list passed to `MakeContext` must be in the **recording**
> > state. The renderer uses it to upload static buffers. Submit it (and wait
> > for the GPU to finish) before issuing any frames.
> [tab] Metal
>
> Header: `rive/renderer/metal/render_context_metal_impl.h`
>
> ```objc theme={null}
> #import "rive/renderer/metal/render_context_metal_impl.h"
>
> using namespace rive::gpu;
>
> id device = MTLCreateSystemDefaultDevice();
>
> RenderContextMetalImpl::ContextOptions opts;
> std::unique_ptr rc =
> RenderContextMetalImpl::MakeContext(device, opts);
> ```
>
> Pass an `id` per frame via
> `FlushResources::externalCommandBuffer`. Rive does **not** present — you
> own the `CAMetalLayer` and the `present` call.
> [tab] Vulkan
>
> Header: `rive/renderer/vulkan/render_context_vulkan_impl.hpp`
>
> ```cpp theme={null}
> #include "rive/renderer/vulkan/render_context_vulkan_impl.hpp"
>
> using namespace rive::gpu;
>
> VulkanFeatures features;
> features.independentBlend = true; // detected from device features
> // ... fill out from VkPhysicalDeviceFeatures ...
>
> std::unique_ptr rc =
> RenderContextVulkanImpl::MakeContext(
> instance,
> physicalDevice,
> device,
> features,
> vkGetInstanceProcAddr);
> ```
>
> Each frame:
>
> * Set `FlushResources::externalCommandBuffer` to a recording
> `VkCommandBuffer`.
>
> * Set `FlushResources::currentFrameNumber` to the frame index you'll signal,
> and `safeFrameNumber` to the most recent frame whose fence you've waited on.
>
> > [!NOTE]
> >
> > Vulkan is the only backend that supports `FrameDescriptor::virtualTileWidth`
> > / `virtualTileHeight` (frame splitting), useful for letting other
> > workloads pre-empt Rive on tiled GPUs.
> [tab] OpenGL / WebGL
>
> Header: `rive/renderer/gl/render_context_gl_impl.hpp`
>
> ```cpp theme={null}
> #include "rive/renderer/gl/render_context_gl_impl.hpp"
> #include "rive/renderer/gl/render_target_gl.hpp"
>
> using namespace rive::gpu;
>
> RenderContextGLImpl::ContextOptions opts;
> // opts.disableFragmentShaderInterlock = true; // if your driver lies
>
> std::unique_ptr rc = RenderContextGLImpl::MakeContext(opts);
> ```
>
> Construct a render target that wraps either an external texture or an
> existing FBO — the doc graph stays the same, only the binding differs:
>
> ```cpp theme={null}
> // Render into a texture you own.
> rcp target =
> make_rcp(width, height);
> target->setTargetTexture(externalTextureID); // GLuint, you keep ownership
>
> // Or, render into an existing FBO you own.
> rcp target =
> make_rcp(
> width, height, fboId, sampleCount);
> ```
>
> Prefer `TextureRenderTargetGL` when you can — `FramebufferRenderTargetGL`
> often has to render to an offscreen texture and blit back, because the
> external FBO is usually not readable.
>
> Capability tiers Rive will auto-select between:
>
> * **Pixel Local Storage** (best — Apple GPUs, modern mobile).
> * **Fragment Shader Interlock** (NVIDIA, Intel via `GL_INTEL_…`).
> * **R/W Texture / EXT_shader_pixel_local_storage** fallbacks.
> * **MSAA** path on truly minimal drivers.
>
> For WebGL 2: the same header builds against Emscripten — `MakeContext`
> will pick the WebGL-compatible PLS implementation automatically.
## Picking modes per frame
`RenderContext::FrameDescriptor` carries flags that change the rendering
algorithm:
| Field | Effect |
| - | - |
| `loadAction` | `clear` (default) / `preserveRenderTarget` / `dontCare`. |
| `clearColor` | ARGB; only used when `loadAction == clear`. |
| `msaaSampleCount` | Nonzero forces MSAA mode and disables PLS. |
| `disableRasterOrdering` | Forces the atomic path even where rasterizer ordering is supported. |
| `ditherMode` | `none` or `interleavedGradientNoise` (default). |
Most apps leave these at defaults. Override only when you see a specific issue
on a specific GPU.
## Choosing a backend
| Platform | Recommendation |
| - | - |
| Windows desktop | **D3D11** if you only need 11-class hardware, **D3D12** for newer engines. |
| macOS / iOS | **Metal**. |
| Android | **Vulkan** on supported devices, **GLES** as fallback. |
| Linux desktop | **Vulkan**. |
| Web | **WebGL 2** via `RenderContextGLImpl` (build with Emscripten). |
| Game console | Talk to Rive — separate runtimes ship for PS5, Xbox, and Switch. |
# Rendering Loop
Source: https://rive.app/docs/runtimes/cpp/rendering-loop
What happens between beginFrame and flush — and how to drive it.
Each frame goes through three phases:
1. **Advance.** `sm->advanceAndApply(dt)` updates state machines, animations, layout, and data bindings.
2. **Record.** `RiveRenderer` records draw commands into the active `RenderContext`.
3. **Submit.** `renderContext->flush(...)` builds the GPU work and lets the
backend submit it.
```cpp theme={null}
// 1. Advance.
sm->advanceAndApply(dt);
// 2. Record draws.
RenderContext::FrameDescriptor frame{};
frame.renderTargetWidth = w;
frame.renderTargetHeight = h;
frame.clearColor = 0xff202020;
renderContext->beginFrame(frame);
RiveRenderer renderer(renderContext.get());
renderer.save();
renderer.align(Fit::contain, Alignment::center,
AABB(0, 0, w, h), artboard->bounds());
sm->draw(&renderer);
renderer.restore();
// 3. Submit.
RenderContext::FlushResources flush{};
flush.renderTarget = renderTarget.get();
renderContext->flush(flush);
```
## `FrameDescriptor`
Configures the upcoming frame. Values are reset every `beginFrame`.
| Field | Default | Purpose |
| - | - | - |
| `renderTargetWidth` / `renderTargetHeight` | 0 | Must match your render target. |
| `loadAction` | `clear` | `clear` / `preserveRenderTarget` / `dontCare`. |
| `clearColor` | 0 | ARGB; only used with `loadAction == clear`. |
| `msaaSampleCount` | 0 | Nonzero forces MSAA mode. |
| `disableRasterOrdering` | false | Forces atomic mode even when raster-ordering is supported. |
| `ditherMode` | `interleavedGradientNoise` | `none` to disable. |
| `virtualTileWidth` / `virtualTileHeight` | 0 | Vulkan-only frame tiling for pre-emption. |
## `FlushResources`
Carries everything the backend needs to submit the recorded work.
| Field | Use |
| - | - |
| `renderTarget` | The `RenderTarget*` you bound this frame's backbuffer to. |
| `externalCommandBuffer` | Backend command buffer — `VkCommandBuffer` (Vulkan), `id` (Metal), `WGPUCommandEncoder` (WebGPU). Unused on D3D11 / GL. |
| `currentFrameNumber` | Monotonic frame ID for resource lifetime tracking. |
| `safeFrameNumber` | Most recent frame whose GPU work has retired (i.e. fence has signaled). Resources last used on or before this frame can be recycled. |
On D3D12, Vulkan, and Metal you must update `currentFrameNumber` and
`safeFrameNumber` every frame against your fence values. Otherwise the
renderer can't safely recycle staging buffers and you'll either see
overwrites mid-flight or unbounded memory growth.
## Fixed-timestep accumulator
State machines and animations are deterministic at fixed `dt`s. Wrap your
real-elapsed-time delta in an accumulator so playback is reproducible across
frame rates:
```cpp theme={null}
constexpr float kFixedSimDt = 1.f / 120.f;
constexpr float kMaxFrameDt = 0.25f; // cap after stalls
void tick(float realDt) {
if (realDt > kMaxFrameDt) realDt = kMaxFrameDt;
accumulator += realDt;
while (accumulator >= kFixedSimDt) {
sm->advanceAndApply(kFixedSimDt);
accumulator -= kFixedSimDt;
}
drawFrame();
}
```
The cap (`kMaxFrameDt`) prevents catch-up storms after the app gets paused
in a debugger or backgrounded by the OS.
## Resize handling
Three things have to happen on a resize:
1. Resize your swap-chain / framebuffer.
2. Re-create the `RenderTarget`.
3. Either feed the new size into the artboard (for `Fit::layout`) or call
`resetSize()`, then run `advanceAndApply(0)` so layout solves before the
next draw.
```cpp theme={null}
void onResize(uint32_t w, uint32_t h) {
swapChain->ResizeBuffers(0, w, h, DXGI_FORMAT_UNKNOWN, 0);
auto* impl = renderContext->static_impl_cast();
renderTarget = impl->makeRenderTarget(w, h);
if (fit == Fit::layout) {
artboard->width(static_cast(w));
artboard->height(static_cast(h));
} else {
artboard->resetSize();
}
sm->advanceAndApply(0.f);
}
```
## Aligning Artboard to Viewport
Use `computeAlignment` (or `Renderer::align`) to map artboard-space into the
viewport. Stash the matrix — you'll need its inverse to convert pointer
coordinates back into artboard-space.
```cpp theme={null}
#include "rive/renderer.hpp"
Mat2D align = computeAlignment(
Fit::contain, Alignment::center,
AABB(0, 0, w, h),
artboard->bounds());
renderer.save();
renderer.transform(align);
sm->draw(&renderer);
renderer.restore();
// Later, on input:
Vec2D pt = align.invertOrIdentity() * Vec2D{(float)mx, (float)my};
sm->pointerMove(pt);
```
## When to skip a frame
`advanceAndApply` returns `true` if the state machine has more work; `false` if
everything has settled. For animations that have looped to rest, you can
skip both the advance step and the draw call, dropping CPU/GPU usage to
zero between user inputs.
Pointer events and external view-model writes can wake the state machine back up —
re-draw at least once after each.
## Tear-down
```cpp theme={null}
sm.reset();
artboard.reset();
file = nullptr;
renderTarget = nullptr;
renderContext.reset(); // last
```
Always destroy Rive objects **before** the `RenderContext` and the
underlying GPU device. Rive objects hold reference-counted GPU resources;
killing the device first leaves them with dangling handles and crashes on
release.
# State Machines
Source: https://rive.app/docs/runtimes/cpp/state-machines
Advance state machines and forward pointer events.
`StateMachineInstance` is the unit of playback in C++:
```cpp theme={null}
class StateMachineInstance {
public:
bool advanceAndApply(float elapsedSeconds);
void draw(Renderer*);
HitResult pointerDown(Vec2D, int pointerId = 0);
HitResult pointerMove(Vec2D, float timeStamp = 0, int pointerId = 0);
HitResult pointerUp(Vec2D, int pointerId = 0);
HitResult pointerExit(Vec2D, int pointerId = 0);
};
```
To drive a state machine — set values, fire triggers, react to changes —
use **Data Binding**. See [Data Binding](/docs/runtimes/cpp/data-binding).
## Advancing
`advanceAndApply(dt)` runs solvers (state machine, animations, layout, data
bindings) for `dt` seconds and applies the results to the artboard's
component graph. Call it before every draw:
```cpp theme={null}
sm->advanceAndApply(deltaSeconds);
sm->draw(&renderer);
```
A return value of `true` means the state machine is still animating and the next
frame should re-draw. `false` means everything has settled.
> [!TIP]
>
> Use a **fixed timestep** accumulator. State machines and animations are
> numerically deterministic at fixed steps, which keeps playback identical
> across frame rates. See [Rendering Loop](/docs/runtimes/cpp/rendering-loop).
### Forcing a Layout pass
Pass `dt = 0` to re-solve layout without advancing time. Useful right after
resizing the window or changing the artboard's `width()` / `height()`:
```cpp theme={null}
artboard->width(newWidth);
artboard->height(newHeight);
sm->advanceAndApply(0.f);
```
## Pointer events
A state machine listens for pointer events on `Listener` components placed
in the editor. Map your window-space coordinates into **artboard-local**
space before forwarding:
```cpp theme={null}
#include "rive/renderer.hpp"
Mat2D align = computeAlignment(
Fit::contain,
Alignment::center,
AABB(0, 0, windowWidth, windowHeight),
artboard->bounds());
Vec2D toArtboard(int x, int y) {
return align.invertOrIdentity() * Vec2D{(float)x, (float)y};
}
sm->pointerMove(toArtboard(mx, my));
sm->pointerDown(toArtboard(mx, my));
sm->pointerUp(toArtboard(mx, my));
sm->pointerExit(toArtboard(mx, my));
```
`HitResult` returns one of three values, which tells you how to route the
same event to other UI behind Rive:
* `none` — the event passed through Rive without firing a listener.
Forward it to whatever UI is behind.
* `hit` — a listener fired, but the shape it's on is transparent. Rive
isn't blocking the event; forward it as well.
* `hitOpaque` — a listener fired and the shape is opaque. Rive consumed
the event; don't forward.
## Reading state changes
After each `advanceAndApply` you can introspect what happened on a
`StateMachineInstance`. Call directly on your `StateMachineInstance`:
```cpp theme={null}
for (size_t i = 0, n = sm->stateChangedCount(); i < n; ++i) {
const LayerState* s = sm->stateChangedByIndex(i);
// s->name(), s->is(), etc.
}
```
This is the hook you use to react in C++ to states defined in the `.riv`
file — log analytics, play a sound, fire a callback into your engine.
# Rive Runtime Demos & Starters
Source: https://rive.app/docs/runtimes/demos
Quick examples to get you up and running.
# Flutter API Reference
Source: https://rive.app/docs/runtimes/flutter/api-reference
Explore the full Rive Flutter API, including widgets, controllers, and runtime classes.
If you're just getting started, check out the [Flutter Getting Started](/docs/runtimes/flutter/flutter) guide instead.
> [card] [View Flutter API Reference](https://pub.dev/documentation/rive/latest/rive/)
>
> Open the full API docs on pub.dev
# Artboards
Source: https://rive.app/docs/runtimes/flutter/artboards
Selecting which artboard to render at runtime
For more information on creating artboards in the Rive editor, please refer to [Artboards](/docs/editor/fundamentals/artboards).
## Choosing an Artboard
When a Rive object is instantiated or when a Rive file is rendered, you can specify the artboard to use. If no artboard is given, the [default artboard](/docs/editor/fundamentals/artboards#default-state-machine), as set in the Rive editor, is used. If no default artboard is set, the first artboard is used.
Only one artboard can be rendered at a time.
### Creating an artboard
Manually create an artboard:
```dart theme={null}
// Default artboard
final artboard = riveFile.defaultArtboard();
// Artboard named
final artboard = riveFile.artboard('My Artboard');
// Artboard at index
final artboard = riveFile.artboardAt(0);
```
### Specifying an artboard
Specify the artboard to use in `RiveWidgetController` or `RiveWidgetBuilder`:
```dart theme={null}
// Default artboard
final artboardSelector = ArtboardSelector.byDefault();
// Artboard named
final artboardSelector = ArtboardSelector.byName('My Artboard');
// Artboard at index
final artboardSelector = ArtboardSelector.byIndex(0);
// Pass to RiveWidgetController
final controller = RiveWidgetController(
riveFile,
artboardSelector: artboardSelector,
);
// Pass to RiveWidgetBuilder
return RiveWidgetBuilder(
fileLoader: fileLoader,
artboardSelector: ArtboardSelector.byName('My Artboard'),
builder: (context, state) {
// return a widget
},
);
```
# Caching a Rive File
Source: https://rive.app/docs/runtimes/flutter/caching-a-rive-file
Under most circumstances a `.riv` file should load quickly and managing the `RiveFile` yourself is not necessary. But if you intend to use the same `.riv` file in multiple parts of your application, or even on the same screen, it might be advantageous to load the file once and keep it in memory.
## Example usage
In Flutter, you are responsible for managing the lifecycle of a Rive file. You can create a `File` object directly, or use the `FileLoader` convenience class with `RiveWidgetBuilder`. In both cases, you must call `dispose()` on the object when it's no longer needed to free up memory.
```dart theme={null}
import 'package:flutter/material.dart';
import 'package:rive/rive.dart';
class CachedPage extends StatefulWidget {
const CachedPage({super.key});
@override
State createState() => _CachedPageState();
}
class _CachedPageState extends State {
var _isRivLoaded = false;
// This is where our cached file will go.
late File _riveFile;
@override
void initState() {
super.initState();
// Once initialized, build the layout by updating _isRivLoaded.
_initRive().whenComplete(
() => setState(() {
_isRivLoaded = true;
}),
);
}
Future _initRive() async {
// Retrieve the Rive file from assets.
_riveFile = (await File.asset(
"assets/rewards_demo.riv",
riveFactory: Factory.rive,
))!;
}
@override
void dispose() {
_riveFile.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (_isRivLoaded) {
// Both widgets can use the same Rive file because we cached it as state.
final widget1 = RiveWidget(controller: RiveWidgetController(_riveFile));
final widget2 = RiveWidget(controller: RiveWidgetController(_riveFile));
return Scaffold(
body: Row(
children: [
Expanded(child: widget1),
Expanded(child: widget2),
],
),
);
} else {
return CircularProgressIndicator();
}
}
}
```
> [!TIP]
>
> To optimize memory usage, reuse the same `File` object across multiple `RiveWidget` instances if they use the same `.riv` file. This ensures the file is loaded only once and shared in memory.
> [!WARNING]
>
> After a `File` is disposed, it cannot be used again. To use the same `.riv` file, create a new `File` object.
#### Managing state
How you keep the Rive `File` alive and share it with widgets depends on your state management approach. For global access, load the file in `main` or during app startup, and expose it using a package like [Provider](https://pub.dev/packages/provider). If the file is only needed in a specific part of your app, consider loading the file only when required.
#### Memory
Managing the file yourself gives you fine-grained control over memory usage, especially when the same Rive file is used in multiple places or simultaneously in several widgets. Use [Flutter DevTools memory tooling](https://docs.flutter.dev/tools/devtools/memory#memory-view-guide) to monitor and optimize memory if needed.
#### Network assets
To load a Rive file from the Internet, use `File.url('YOUR:URL')`. For network assets, cache the file in memory to avoid repeated downloads and unnecessary decoding of the file.
# Data Binding
Source: https://rive.app/docs/runtimes/flutter/data-binding
Connect your code to bound editor elements using View Models
Before engaging with the runtime data binding APIs, it is important to familiarize yourself with the core concepts presented in the [Overview](/docs/editor/data-binding/overview).
# View Models
View models describe a set of properties, but cannot themselves be used to get or set values - that is the role of [view model instances](#view-model-instances).
To begin, we need to get a reference to a particular view model. This can be done either by index, by name, or the default for a given artboard, and is done from the Rive file. The default option refers to the view model assigned to an artboard by the dropdown in the editor.
> [!NOTE]
>
> If you're using a `RiveWidgetController`, you can skip the step of creating a `ViewModel`. Go to [View Model Instances](#view-model-instances).
```dart theme={null}
// Get reference to the File and Artboard
final file = await File.asset(
'assets/my_file.riv',
riveFactory: Factory.rive,
);
final artboard = file!.defaultArtboard()!;
// Get reference by name
file.viewModelByName("My View Model");
// Get reference by index
for (var i = 0; i < file.viewModelCount; i++) {
final indexedVM = file.viewModelByIndex(i);
}
// Get reference to the default view model for an artboard
final defaultVM = file.defaultArtboardViewModel(artboard);
// Dispose the view model when you're no longer using it
viewModel.dispose();
```
# View Model Instances
Once we have a reference to a view model, it can be used to create an instance. When creating an instance, you have four options:
1. Create a blank instance - Fill the properties of the created instance with default values as follows:
| Type | Value |
| - | - |
| Number | 0 |
| String | Empty string |
| Boolean | False |
| Color | 0xFF000000 |
| Trigger | Untriggered |
| Enum | The first value |
| Image | No image |
| Font | No font |
| Artboard | No artboard |
| List | Empty list |
| Nested view model | Null |
2. Create the default instance - Use the instance labelled "Default" in the editor. Usually this is the one a designer intends as the primary one to be used at runtime.
3. Create by index - Using the order returned when iterating over all available instances. Useful when creating multiple instances by iteration.
4. Create by name - Use the editor's instance name. Useful when creating a specific instance.
> [!NOTE]
>
> In some samples, due to the wordiness of "view model instance", we use the abbreviation "VMI", as well as "VM" for "view model".
If you're using `RiveWidgetController`:
```dart theme={null}
// Get reference to the File
file = await File.asset(
'assets/rewards.riv',
riveFactory: Factory.rive,
);
// Create a controller
controller = RiveWidgetController(file!);
// Data bind by name
viewModelInstance = controller.dataBind(DataBind.byName('My View Model'));
// Data bind by index
viewModelInstance = controller.dataBind(DataBind.byIndex(0));
// Auto data bind
viewModelInstance = controller.dataBind(DataBind.auto());
// Bind some existing view model instance to the controller:
viewModelInstance = controller.dataBind(DataBind.byInstance(someViewModelInstance));
// Dispose of objects you created when no longer needed
viewModelInstance.dispose();
controller.dispose();
file.dispose();
```
If you want to manage the creation of view model instances yourself:
```dart theme={null}
final vm = file.viewModelByName("My View Model")!;
// Create blank
final vmiBlank = vm.createInstance();
// Create default
final vmiDefault = vm.createDefaultInstance();
// Create by index
for (int i = 0; i < vm.instanceCount; i++) {
final vmiIndexed = vm.createInstanceByIndex(i);
}
// Create by name
final vmiNamed = vm.createInstanceByName("My Instance");
// Dispose the view model instance
viewModelInstance.dispose();
```
### Binding
The created instance can then be assigned to a state machine or artboard. This establishes the bindings set up at edit time.
It is preferred to assign to a state machine, as this will automatically apply the instance to the artboard as well. Only assign to an artboard if you are not using a state machine, i.e. your file is static or uses linear animations.
> [!NOTE]
>
> The initial values of the instance are not applied to their bound elements until the state machine or artboard advances.
If you're using `RiveWidgetController` the binding happens automatically when you call any of the following:
```dart theme={null}
viewModelInstance = controller.dataBind(DataBind.auto());
viewModelInstance = controller.dataBind(DataBind.byName('My View Model'));
viewModelInstance = controller.dataBind(DataBind.byIndex(0));
viewModelInstnace = controller.dataBind(DataBind.byInstance(someViewModelInstance));
```
Else, you need to make sure to bind the view model instance to the state machine, or artboard.
```dart theme={null}
final file = await File.asset(
'assets/my_file.riv',
riveFactory: Factory.rive,
);
final artboard = file!.defaultArtboard();
final stateMachine = artboard!.defaultStateMachine()!;
final vm = file.defaultArtboardViewModel(artboard)!;
final vmi = vm.createDefaultInstance()!;
// Bind to the state machine. This automatically binds to the artboard as well.
stateMachine.bindViewModelInstance(vmi);
// If you're not using a state machine, bind to the artboard
artboard.bindViewModelInstance(vmi);
```
### Auto-Binding
Alternatively, you may prefer to use auto-binding. This will automatically bind the default view model of the artboard using the default instance to both the state machine and the artboard. The default view model is the one selected on the artboard in the editor dropdown. The default instance is the one marked "Default" in the editor.
```dart theme={null}
// Get reference to the File
file = await File.asset(
'assets/rewards.riv',
riveFactory: Factory.rive,
);
// Create a controller
controller = RiveWidgetController(file!);
// Auto data bind
viewModelInstance = controller.dataBind(DataBind.auto());
// Dispose of objects you created when no longer needed
viewModelInstance.dispose();
controller.dispose();
file.dispose();
```
# Properties
A property is a value that can be read, set, or observed on a view model instance. Properties can be of the following types:
| Type | Supported |
| - | - |
| Floating point numbers | ✅ |
| Booleans | ✅ |
| Triggers | ✅ |
| Strings | ✅ |
| Enumerations | ✅ |
| Colors | ✅ |
| Nested View Models | ✅ |
| Lists | ✅ |
| Images | ✅ |
| Artboards | ✅ |
For more information on version compatibility, see the [Feature Support](/docs/feature-support) page.
### Listing properties
Property descriptors can be inspected on a view model to discover at runtime which are available. These are not the mutable properties themselves though - once again those are on instances. These descriptors have a type and name.
```dart theme={null}
// Access on a ViewModel object
print("Properties: ${viewModel.properties}");
// Access on a ViewModelInstance object
print("Properties: ${viewModelInstance.properties}");
```
### Reading and writing properties
References to these properties can be retrieved by name or path.
Some properties are mutable and have getters, setters, and observer operations for their values. Getting or observing the value will retrieve the latest value set on that property's binding, as of the last state machine or artboard advance. Setting the value will update the value and all of its bound elements.
> [!NOTE]
>
> After setting a property's value, the changes will not apply to their bound elements until the state machine or artboard advances.
```dart theme={null}
// Get reference to the ViewModel instance
final vmi = someExistingViewModelInstance;
final numberProperty = vmi.number("My Number Property")!;
// Get
final numberValue = numberProperty.value;
// Set
numberProperty.value = 10;
// Observe
void onNumberChange(double value) {
print("Number changed to: $value");
}
numberProperty.addListener(onNumberChange);
// Remove listener when done
numberProperty.removeListener(onNumberChange);
// Alternatively, clear all listeners
numberProperty.clearListeners();
// Dispose of the property to clear up resources when you're no longer using it
// This will call `clearListeners()` internally.
numberProperty.dispose();
```
### Nested property paths
View models can have properties of type view model, allowing for arbitrary nesting. You can chain property calls on each instance starting from the root until you get to the property of interest. Alternatively, you can do this through a path parameter, which is similar to a URI in that it is a forward slash delimited list of property names ending in the name of the property of interest.
```dart theme={null}
// Get reference to the ViewModel instance
final vmi = someExistingViewModelInstance;
final nestedNumberByChain = vmi
.viewModel("My Nested View Model")!
.viewModel("My Second Nested VM")!
.number("My Nested Number");
final nestedNumberByPath = vmi.number("My Nested View Model/My Second Nested VM/My Nested Number");
```
### Observability
You can observe changes over time to property values, either by using listeners or a platform equivalent method. Once observed, you will be notified when the property changes are applied by a state machine advance, whether that is a new value that has been explicitly set or if the value was updated as a result of a binding.
```dart theme={null}
// Get reference to the ViewModel instance
final vmi = someExistingViewModelInstance;
final numberProperty = vmi.number("My Number Property")!;
// Get
final numberValue = numberProperty.value;
// Set
numberProperty.value = 10;
// Observe
void onNumberChange(double value) {
print("Number changed to: $value");
}
numberProperty.addListener(onNumberChange);
// Remove listener when done
numberProperty.removeListener(onNumberChange);
// Alternatively, clear all listeners
numberProperty.clearListeners();
// Dispose of the property to clear up resources when you're no longer using it
// This will call `clearListeners()` internally.
numberProperty.dispose();
```
### Images
Image properties let you set and replace raster images at runtime, with each instance of the image managed independently. For example, you could build an avatar creator and dynamically update features — like swapping out a hat — by setting a view model's image property.
> [!NOTE]
>
> See the [Flutter data binding images example](https://github.com/rive-app/rive-flutter/blob/master/example/lib/examples/databinding_images.dart).
```dart theme={null}
// Access the image property by path on a ViewModelInstance object
final imageProperty = viewModelInstance.image('my_image')!; // image property named "my_image"
// Create a RenderImage
final renderImage = await Factory.rive.decodeImage(bytes); // use `Factory.flutter` if you're using the Flutter renderer
// If the image is valid, update the image property value
if (renderImage != null) {
imageProperty.value = renderImage;
}
// You can also set the image property to null to clear it
imageProperty.value = null;
```
### Lists
List properties let you manage a dynamic set of view model instances at runtime. For example, you can build a to-do app where users can add and remove tasks in a scrollable Layout.
See the [Editor section](/docs/editor/data-binding/lists) on creating data bound lists.
A single list property can include different view model types, with each view model tied to its own Component, making it easy to populate a list with a variety of Component instances.
With list properties, you can:
* Add a new view model instance (optionally at an index)
* Remove an existing view model instance (optionally by index)
* Swap two view model instances by index
* Get the size of a list
For more information on list properties, see the [Data Binding List Property](/docs/editor/data-binding/lists#view-model-list-property) editor documentation.
The list API in Flutter is designed to be similar to the [List](https://api.dart.dev/dart-core/List-class.html) class in Dart. It doesn't contain the full API spec of that class, but it does provide the most commonly used methods.
> [!WARNING]
>
> Working with lists can result in errors ([`RangeError`](https://api.flutter.dev/flutter/dart-core/RangeError-class.html)) being thrown if you try to access an index that is out of bounds, or perform other list operations that are not permitted. Similar to the Dart List API.
Access a list property by path on a `ViewModelInstance` object:
```dart Access a List property theme={null}
final todosProperty = viewModelInstance.list('todos')!; // list property named "todos"
print(todosProperty.length); // print the length of the list
```
To add an item you first need to create an instance of the view model that you want to add to the list:
```dart Create a blank view model instance theme={null}
final todoItemVM = riveFile.viewModelByName("TodoItem")!;
final todoItemInstance = todoItemVM.createInstance()!;
```
You can also create an instance from an existing instance (as exported in the Rive Editor), using:
* `createDefaultInstance()`
* `createInstanceByName('exercise')`
* `createInstanceByIndex(0)`.
Then add the instance to the list:
```dart Add an instance to the list theme={null}
todosProperty.add(todoItemInstance);
```
To remove a particular instance from the list, you can use the `remove` method:
```dart Remove an instance from the list theme={null}
todosProperty.remove(todoItemInstance);
```
Other operations:
```dart List operations theme={null}
// Remove at index
todosProperty.removeAt(0); // can throw
// Insert at index
todosProperty.insert(0, todoItemInstance); // can throw
// Swap
todosProperty.swap(0, 1); // can throw
// First
ViewModelInstance todo = todosProperty.first(); // can throw
// Last
ViewModelInstance todo = todosProperty.last(); // can throw
// First or null
ViewModelInstance? todo todosProperty.firstOrNull(); // will return null if the list is empty
// Last or null
ViewModelInstance? todosProperty.lastOrNull(); // will return null if the list is empty
// Access/set directly by index
final instance = todosProperty[0]; // can throw
todosProperty[0] = todoItemInstance; // can throw
// Instance at index
todosProperty.instanceAt(2); // can throw
// Length
todosProperty.length;
```
### Artboards
Artboard properties allows you to swap out entire components at runtime. This is useful for creating modular components that can be reused across different designs or applications, for example:
* Creating a skinning system that supports a large number of variations, such as a character creator where you can swap out different body parts, clothing, and accessories.
* Creating a complex scene that is a composition of various artboards loaded from various different Rive files (drawn to a single canvas/texture/widget).
* Reducing the size (complexity) of a single Rive file by breaking it up into smaller components that can be loaded on demand and swapped in and out as needed.
> [!NOTE]
>
> See the [Flutter data binding artboards example](https://github.com/rive-app/rive-flutter/blob/master/example/lib/examples/databinding_artboards.dart).
Artboard properties work with the `BindableArtboard` class, which is different from the regular `Artboard` class in the package.
`BindableArtboard` is a runtime wrapper for interacting with artboards through data binding. These instances reference existing artboards in your file, so no additional setup is required in the Rive Editor.
```dart theme={null}
// Artboard property to bind
final artboardProp = viewModelInstance.artboard('artboardPropertyName')!;
// Create a bindable artboard
final bindableArtboard = riveFile.artboardToBind('artboardName')!;
artboardProp.value = bindableArtboard;
```
### Enums
Enums properties come in two flavors: system and user-defined. In practice, you will not need to worry about the distinction, but just be aware that system enums are available in any Rive file that binds to an editor-defined enum set, representing options from the editor's dropdowns, where user-defined enums are those defined by a designer in the editor.
Enums are string typed. The Rive file contains a list of enums. Each enum in turn has a name and a list of strings.
```dart theme={null}
// Access on a File object
print("Data enums: ${file.enums}");
```
## Examples
* [Data binding overview](https://github.com/rive-app/rive-flutter/blob/master/example/lib/examples/databinding.dart)
* [Data binding images](https://github.com/rive-app/rive-flutter/blob/master/example/lib/examples/databinding_images.dart)
* [Data binding artboards](https://github.com/rive-app/rive-flutter/blob/master/example/lib/examples/databinding_artboards.dart)
* [Data binding lists](https://github.com/rive-app/rive-flutter/blob/master/example/lib/examples/databinding_lists.dart)
# FAQ
Source: https://rive.app/docs/runtimes/flutter/faq
Common Flutter runtime issues and fixes.
## Where should I look first when my Flutter build fails?
Start with these docs:
* [Flutter runtime troubleshooting](/docs/runtimes/flutter/flutter#troubleshooting)
* [Rive Native troubleshooting](/docs/runtimes/flutter/rive-native#troubleshooting)
* [Building `rive_native`](/docs/runtimes/flutter/rive-native#building-rive-native)
* [Flutter migration guide](/docs/runtimes/flutter/migration-guide)
Most build issues come from setup/version mismatches, stale native artifacts, or skipped native setup. A clean rebuild usually helps:
```bash theme={null}
flutter clean
flutter pub get
flutter run
```
If native libraries were not downloaded, run the `rive_native` setup CLI for your target platform:
```bash theme={null}
dart run rive_native:setup --verbose --clean --platform
```
Replace `` with the platform you are building for (for example, `android` or `macos`).
You can also provide multiple platforms as a comma-separated list (for example, `android,ios,macos`).
If you still see setup errors, follow [Rive Native troubleshooting](/docs/runtimes/flutter/rive-native#troubleshooting). For Android-specific setup issues, see the [Android notes](/docs/runtimes/flutter/rive-native#android).
## `LateInitializationError: Field 'makeFlutterFactory' has not been initialized`
If you see an error like `LateInitializationError: Field 'makeFlutterFactory' has not been initialized`, make sure you initialize Rive before showing any Rive widgets.
Call `RiveNative.init()` early (for example in `main()`), before creating or using `Factory.flutter`/`Factory.rive`.
> [tab] 0.14.x
>
> ```dart theme={null}
> import 'package:flutter/widgets.dart';
> import 'package:rive/rive.dart';
>
> Future main() async {
> WidgetsFlutterBinding.ensureInitialized();
> await RiveNative.init();
> runApp(const MyApp());
> }
> ```
> [tab] 0.15.0 and later
>
> Call `init()` the same way and handle its result. See [Initializing Rive](/docs/runtimes/flutter/flutter#initializing-rive).
>
> This error can also mean `init()` returned `RiveNativeInitFailed`. Its `message` says why.
## "Too many active WebGL contexts" warnings on web
Every `Factory.rive` widget that owns its texture holds a live WebGL context, and browsers cap those. Exhausting the cap can also cause blank or frozen Rive widgets and CanvasKit context-loss errors. See [WebGL contexts (web)](/docs/runtimes/flutter/flutter#webgl-contexts-web) for how contexts are released and reused.
To stay under the cap:
* Draw multiple widgets into one shared texture with a [RivePanel](/docs/runtimes/flutter/flutter#rivepanel) — one context in total.
* Dispose Rive widgets you no longer show — that releases their WebGL contexts.
Set `RiveNative.debugRenderTextureLogging = true` to confirm you're hitting the cap: it logs texture create, reuse, and release with live WebGL context counts.
## How to enable 16KB page support on Android?
Rive Flutter `0.14.x` includes 16KB page support by default.
If you're on `0.13.x`, you need to specify the NDK version used by setting `rive.ndk.version=28.1.13356709` in your `gradle.properties` file.
This gives you 16KB page support and flexibility to control the NDK used for future updates.
For additional context, see [rive-flutter issue #479](https://github.com/rive-app/rive-flutter/issues/479).
## Why do I get `Failed to lookup symbol` in archived builds with Swift Package Manager?
iOS and macOS apps that use Swift Package Manager can fail to load Rive files once Xcode archives them for TestFlight, the App Store or distribution. The error names `loadRiveFile`, `init` or `makeFlutterFactory`. Archiving strips symbols that Rive looks up at runtime.
From `rive` `0.15.0`, archived apps load Rive files without extra setup.
On earlier versions, select the **Runner** target in Xcode, open **Build Settings** > **Strip Style**, and change **All Symbols** to **Non-Global Symbols**.
For additional context, see rive-flutter issues [#617](https://github.com/rive-app/rive-flutter/issues/617) and [#641](https://github.com/rive-app/rive-flutter/issues/641).
# Flutter
Source: https://rive.app/docs/runtimes/flutter/flutter
Flutter runtime for Rive.
> [!WARNING]
>
> Note that certain Rive features may not be supported yet for a particular runtime, or may require using the Rive Renderer.
>
> For more details, refer to the [feature support](/docs/feature-support/) and [choosing a renderer](/docs/runtimes/choose-a-renderer/) pages.
## Overview
This guide documents how to use the Rive Flutter runtime to easily integrate Rive graphics in your Flutter apps.
> [!NOTE]
>
> There is a new major version of Rive Flutter, `0.15.x`, currently available as a dev release. See the [migration guide](/docs/runtimes/flutter/migration-guide#version-0-15-0) for what changed. Try it out and let us know what you think.
> [!NOTE]
>
> Already using Rive Flutter? See our [Migration
> Guide](/docs/runtimes/flutter/migration-guide) for information on adopting the
> latest version.
## Quick start
See our [example app](https://github.com/rive-app/rive-flutter/tree/master/example).
## Getting started
Follow the steps below to integrate Rive into your Flutter apps.
**1. Add the Rive package dependency**
Check out Rive's [pub.dev](https://pub.dev/packages/rive) page to get the latest version.
```yaml theme={null}
# pubspec.yaml
dependencies:
rive: ^0.14.11
```
**2. Import the Rive package**
Import the Rive runtime library in the file you're looking to integrate Rive animations into.
```dart theme={null}
import 'package:rive/rive.dart';
```
Consider doing a named import to avoid conflicts with other libraries:
```dart theme={null}
import 'package:rive/rive.dart' as rive;
```
**3. Initialize Rive**
> [!NOTE]
>
> Call `RiveNative.init()` at the start of your app, for example in `main.dart`. Rive calls it on its own the first time you load a Rive file, but calling it yourself loads Rive before your first graphic and, from `0.15.0`, gives you the result. See [Initializing Rive](#initializing-rive).
> [tab] 0.14.x
>
> ```dart theme={null}
> import 'package:rive/rive.dart';
>
> Future main() async {
> WidgetsFlutterBinding.ensureInitialized();
> // Call init before using Rive.
> await RiveNative.init();
> runApp(const MyApp());
> }
> ```
> [tab] 0.15.0 and later
>
> ```dart theme={null}
> import 'package:rive/rive.dart';
>
> bool useFlutterRenderer = false;
>
> /// Pass this wherever you would pass `Factory.rive`.
> Factory get riveFactory =>
> useFlutterRenderer ? Factory.flutter : Factory.rive;
>
> Future main() async {
> WidgetsFlutterBinding.ensureInitialized();
> switch (await RiveNative.init()) {
> case RiveNativeReady():
> break;
> case RiveRendererUnavailable():
> // The Rive Renderer could not initialize. Fall back to Flutter.
> useFlutterRenderer = true;
> case RiveNativeInitFailed():
> // Rive cannot run, and it printed why. Leave Rive content out.
> break;
> }
> runApp(const MyApp());
> }
> ```
>
> The examples below pass `Factory.rive`. Pass `riveFactory` instead so the fallback applies. `RivePanel` and shared textures need `Factory.rive`, so leave them out when `useFlutterRenderer` is `true`.
**4. Add a Rive widget**
There are several ways to render Rive graphics in Flutter. We recommend using the `RiveWidget` and optionally the `RiveWidgetBuilder`, `RivePanel`, or a manually managed shared texture.
* `RiveWidget` is responsible for rendering the graphic and exposing common view configuration.
* `RiveWidgetBuilder` handles file loading, error states, and resource management automatically.
* `RivePanel` is a higher-level inherited widget that creates a shared texture to paint multiple `RiveWidget`s to. Only usable when using the Rive Renderer (`Factory.rive`). This can drastically improve performance when showing many Rive graphics at once by reducing the number of textures and avoiding WebGL context limitations on the web.
* `SharedRenderTexture.create()` and `RiveSurface` let you create and place a shared texture yourself, then pass it to `RiveWidget.sharedTexture`. Use this when the widgets drawing to the texture do not share a common `RivePanel` ancestor, such as siblings, overlays, or separate routes.
> [tab] Using RiveWidgetBuilder
>
> ```dart theme={null}
> class ExampleRiveBuilder extends StatefulWidget {
> const ExampleRiveBuilder({super.key});
>
> @override
> State createState() => _ExampleRiveBuilderState();
> }
>
> class _ExampleRiveBuilderState extends State