Unity3D 背景动态模糊(blur)和截屏方法

本文介绍了在Unity3D中利用OnRenderImage函数进行背景动态模糊和截图的方法。通过挂载在Camera上的组件,获取并处理当前屏幕的RenderTexture,实现动态模糊效果。当需要高亮某个界面时,可以先截图并模糊背景,然后在高亮界面显示模糊背景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

unity 提供了一个函数 OnRenderImage (RenderTexture source, RenderTexture destination) ,只要将这个组件挂载在Camera上面。就能够自动调用,获得当前屏幕的RenderTexture,和需要写入的目标RenderTexture,也就是需要显示的纹理。可见,source就是当前屏幕的纹理数据,可以保存这个数据得到当前屏幕的纹理数据,就相当于截图了,我们也可以通过剪裁采样这个数据,得到一个放大或缩小的截图数据使用。


根据这个接口,unity官方给予了一个blur动态模糊的效果。代码如下:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using DG;
using DG.Tweening;

[ExecuteInEditMode]
[AddComponentMenu("Image Effects/Blur/Blur")]
public class BlurEffect : MonoBehaviour
{	

	/// Blur iterations - larger number means more blur.
	public int iterations = 3;
	
	/// Blur spread for each iteration. Lower values
	/// give better looking blur, but require more iterations to
	/// get large blurs. Value is usually between 0.5 and 1.0.
	public float blurSpread = 0.6f;
	
	
	// --------------------------------------------------------
	// The blur iteration shader.
	// Basically it just takes 4 texture samples and averages them.
	// By applying it repeatedly and spreading out sample locations
	// we get a Gaussian blur approximation.
	 
	public Shader blurShader = null;	

	//private static string blurMatString =

	static Material m_Material = null;
	protected Material material {
		get {
			if (m_Material == null) {
				m_Material = new Material(blurShader);
				m_Material.hideFlags = HideFlags.DontSave;
			}
			return m_Material;
		} 
	}
	
	protected void OnDisable() {
		if( m_Material ) {
			DestroyImmediate( m_Material );
		}

		rawImage = null;
	}	
	
	// --------------------------------------------------------
	
	protected void Start()
	{
		// Disable if we don't support image effects
		if (!SystemInfo.supportsImageEffects) {
			enabled = false;
			return;
		}
		// Disable if the shader can't run on the users graphics card
		if (!blurShader || !material.shader.isSupported) {
			enabled = false;
			return;
		}
	}
	
	// Performs one blur iteration.
	public void FourTapCone (RenderTexture source, RenderTexture dest, int iteration)
	{
		float off = 0.5f + iteration*blurSpread;
		Graphics.BlitMultiTap (source, dest, material,
			new Vector2(-off, -off),
			new Vector2(-off,  off),
			new Vector2( off,  off),
			new Vector2( off, -off)
		);
	}
	
	// Downsamples the texture 
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值