add file open

This commit is contained in:
2020-08-07 22:40:04 +08:00
parent c1e3f992aa
commit f9bedd2c62
115 changed files with 9835 additions and 1096 deletions

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 6d8932d9982404063bbe48b7ba05a442
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: dbace2eb7405e9741a69754cce1dc4de
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,239 @@
/*MIT License
Copyright(c) 2020 Mikhail5412
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Core;
using System;
#if UNITY_EDITOR
namespace UnityAndroidOpenUrl.EditorScripts
{
/// <summary>
/// Static class whose task is to update the package name in AndroidManifest.xml if it has been changed
/// </summary>
[InitializeOnLoad]
public static class PackageNameChanger
{
private const string PLUGINS_DIR = "3rd/AndroidOpener/Plugins";
private const string TEMP_DIR = "Temp";
private const string AAR_NAME = "release.aar";
private const string MANIFEST_NAME = "AndroidManifest.xml";
private const string PROVIDER_PATHS_NAME = "res/xml/filepaths.xml";
private static string pathToPluginsFolder;
private static string pathToTempFolder;
private static string pathToBinary;
private static string lastPackageName = "com.company.product";
private static bool stopedByError;
static PackageNameChanger()
{
pathToPluginsFolder = Path.Combine(Application.dataPath, PLUGINS_DIR);
if(!Directory.Exists(pathToPluginsFolder))
{
Debug.LogError("Plugins folder not found. Please re-import asset. See README.md for details...");
return;
}
pathToTempFolder = Path.Combine(pathToPluginsFolder, TEMP_DIR);
pathToBinary = Path.Combine(pathToPluginsFolder, AAR_NAME);
if (!File.Exists(pathToBinary))
{
Debug.LogError("File release.aar not found. Please re-import asset. See README.md for details...");
return;
}
EditorApplication.update += Update;
TryUpdatePackageName();
}
static void Update()
{
if (stopedByError)
return;
if (lastPackageName != PlayerSettings.applicationIdentifier)
{
TryUpdatePackageName();
}
}
private static void TryUpdatePackageName()
{
FileInfo fileInfo = new FileInfo(pathToBinary);
if(!IsFileAlreadyOpen(fileInfo))
{
RepackBinary();
}
}
private static void RepackBinary()
{
try
{
ExtractBinary();
}
catch (Exception e)
{
Debug.LogError("Extract release.aar error: " + e.Message);
stopedByError = true;
return;
}
ChangePackageName();
try
{
ZippingBinary();
}
catch (Exception e)
{
Debug.LogError("Zipping release.aar error: " + e.Message);
stopedByError = true;
return;
}
Directory.Delete(pathToTempFolder, true);
}
private static void ExtractBinary()
{
if (!File.Exists(pathToBinary))
{
throw new Exception("File release.aar not found. Please reimport asset. See README.md for details...");
}
if (!Directory.Exists(pathToTempFolder))
{
Directory.CreateDirectory(pathToTempFolder);
}
using (FileStream fs = new FileStream(pathToBinary, FileMode.Open))
{
using (ZipFile zf = new ZipFile(fs))
{
for (int i = 0; i < zf.Count; ++i)
{
ZipEntry zipEntry = zf[i];
string fileName = zipEntry.Name;
if (zipEntry.IsDirectory)
{
Directory.CreateDirectory(Path.Combine(pathToTempFolder, fileName));
continue;
}
byte[] buffer = new byte[4096];
using (Stream zipStream = zf.GetInputStream(zipEntry))
{
using (FileStream streamWriter = File.Create(Path.Combine(pathToTempFolder, fileName)))
{
StreamUtils.Copy(zipStream, streamWriter, buffer);
}
}
}
if (zf != null)
{
zf.IsStreamOwner = true;
zf.Close();
}
}
}
}
private static void ChangePackageName()
{
string manifestPath = Path.Combine(pathToTempFolder, MANIFEST_NAME);
string manifestText = File.ReadAllText(manifestPath);
int manifestPackageNameStartIndex = manifestText.IndexOf("package=\"") + 9;
int manifestPackageNameEndIndex = manifestText.IndexOf("\">", manifestPackageNameStartIndex);
string manifestPackageName = manifestText.Substring(manifestPackageNameStartIndex, manifestPackageNameEndIndex - manifestPackageNameStartIndex);
manifestText = manifestText.Replace("package=\"" + manifestPackageName, "package=\"" + PlayerSettings.applicationIdentifier);
manifestText = manifestText.Replace("android:authorities=\"" + manifestPackageName, "android:authorities=\"" + PlayerSettings.applicationIdentifier);
File.WriteAllText(manifestPath, manifestText);
string filepathsPath = Path.Combine(pathToTempFolder, PROVIDER_PATHS_NAME);
string filepathsText = File.ReadAllText(filepathsPath);
int filepathsPackageNameStartIndex = filepathsText.IndexOf("data/") + 5;
int filepathsPackageNameEndIndex = filepathsText.IndexOf("\" name", filepathsPackageNameStartIndex);
string filepathsPackageName = filepathsText.Substring(filepathsPackageNameStartIndex, filepathsPackageNameEndIndex - filepathsPackageNameStartIndex);
filepathsText = filepathsText.Replace("data/" + filepathsPackageName, "data/" + PlayerSettings.applicationIdentifier);
File.WriteAllText(filepathsPath, filepathsText);
lastPackageName = PlayerSettings.applicationIdentifier;
}
private static void ZippingBinary() // используется ДОзапись, обычным методом .Add(filePath, entryName), для перезаписи с нуля нужно использовать ZipOutputStream zipToWrite = new ZipOutputStream(zipStream) и FileStream targetFile
{
if (!File.Exists(pathToBinary))
{
throw new Exception("File release.aar not found. Please reimport asset. See README.md for details...");
}
if (!Directory.Exists(pathToTempFolder))
{
throw new Exception("Temp folder not found. See README.pdf for details...");
}
using (FileStream zipStream = new FileStream(pathToBinary, FileMode.Open))
{
using (ZipFile zipFile = new ZipFile(zipStream))
{
zipFile.BeginUpdate();
zipFile.Add(Path.Combine(pathToTempFolder, MANIFEST_NAME), MANIFEST_NAME);
zipFile.Add(Path.Combine(pathToTempFolder, PROVIDER_PATHS_NAME), PROVIDER_PATHS_NAME);
zipFile.CommitUpdate();
}
}
}
private static bool IsFileAlreadyOpen(FileInfo file)
{
try
{
using (FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
{
stream.Close();
}
}
catch (Exception e)
{
Debug.LogError(e.ToString() + ": " + e.Message);
stopedByError = true;
return true;
}
return false;
}
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ee86983896a431840a78dbe69fb91189
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 01dcac85b4f1656418d69de13cafc0e6
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

View File

@@ -0,0 +1,32 @@
fileFormatVersion: 2
guid: cbf7fb971dec3432db468a27adbc4fcb
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
Android: Android
second:
enabled: 1
settings: {}
- first:
Any:
second:
enabled: 0
settings: {}
- first:
Editor: Editor
second:
enabled: 0
settings:
DefaultValueInitialized: true
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 17969fed461284447af370c88b439a3e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,75 @@
/*MIT License
Copyright(c) 2020 Mikhail5412
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UnityAndroidOpenUrl
{
//string[] mimeTypes =
// {"application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
// "application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
// "application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
// "text/plain",
// "application/pdf",
// "application/zip"};
public static class AndroidOpenUrl
{
public static void OpenFile(string url, string dataType = "")//"application/pdf"
{
AndroidJavaObject clazz = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = clazz.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaObject intent = new AndroidJavaObject("android.content.Intent");
intent.Call<AndroidJavaObject>("addFlags", intent.GetStatic<int>("FLAG_GRANT_READ_URI_PERMISSION"));
intent.Call<AndroidJavaObject>("setAction", intent.GetStatic<string>("ACTION_VIEW"));
var apiLevel = new AndroidJavaClass("android.os.Build$VERSION").GetStatic<int>("SDK_INT");
AndroidJavaObject uri;
if (apiLevel > 23)
{
AndroidJavaClass fileProvider = new AndroidJavaClass("android.support.v4.content.FileProvider");
AndroidJavaObject file = new AndroidJavaObject("java.io.File", url);
AndroidJavaObject unityContext = currentActivity.Call<AndroidJavaObject>("getApplicationContext");
string packageName = unityContext.Call<string>("getPackageName");
string authority = packageName + ".fileprovider";
uri = fileProvider.CallStatic<AndroidJavaObject>("getUriForFile", unityContext, authority, file);
}
else
{
var uriClazz = new AndroidJavaClass("android.net.Uri");
var file = new AndroidJavaObject("java.io.File", url);
uri = uriClazz.CallStatic<AndroidJavaObject>("fromFile", file);
}
if (!string.IsNullOrEmpty(dataType))
{
intent.Call<AndroidJavaObject>("setType", dataType);
}
intent.Call<AndroidJavaObject>("setData", uri);
currentActivity.Call("startActivity", intent);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b07f4973c298676448f66cb780c4f6b2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 90b9e3f91eeb64249b80e8c33636811c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,13 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [0.1.0] - 2020-07-30
### Added
- Init commit

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 73252913ec82f3b4fbb65300a8c44696
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Eduard
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 317c760af475c2540b76a28e3783315c
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,35 @@
# DocumentHandler
Open a document (e.g. PDF) with a corresponding native app.
Since ``Application.OpenURL(...path)`` is not working (anymore?) to open local files on iOS, I searched the internet for another solution (see credits). I found usable code and want to make it more accessible.
## How to install
Just add the plugin via Package Manager with the git url:
```
https://github.com/Draudastic26/document-handler.git#upm
```
## Usage
```csharp
using drstc.DocumentHandler;
...
DocumentHandler.OpenDocument(somePath);
```
## Notes
I just tested this on iOS with a PDF file. Please let me know if you tested this with other document types.
## Contribution
Feel free to create a pull request or an issue!
## Credits
martejpad post in this thread: [https://answers.unity.com/questions/1337996/ios-open-docx-file-from-applicationpersistentdata.html](https://answers.unity.com/questions/1337996/ios-open-docx-file-from-applicationpersistentdata.html)
Unity 2019.4.3f

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: f7c4aa3b47f1f6d418567f4d798595d1
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: eaaf4e73c50a9994a91535ac431ebcec
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,24 @@
using System;
using System.Runtime.InteropServices;
using UnityEngine;
namespace drstc.DocumentHandler
{
public class DocumentHandler : MonoBehaviour
{
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport("__Internal")]
internal static extern bool _OpenDocument(string path);
public static void OpenDocument(string path)
{
_OpenDocument(path);
}
#else
public static void OpenDocument(string path)
{
Application.OpenURL("file:///" + path);
}
#endif
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3d93365ec5d0f214fa3e11145e4b8308
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,3 @@
{
"name": "Drstc.DocumentHandler.Runtime"
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: eca2ed0e95167ad4aa975aab1849e6a5
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c435a9dc757064648be238db0af31815
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 758b72d97ebaec34195e3f662c0334af
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,87 @@
// Credits: https://answers.unity.com/questions/1337996/ios-open-docx-file-from-applicationpersistentdata.html
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface DocumentHandler : NSObject <UIDocumentInteractionControllerDelegate>
{
NSURL * fileURL;
}
- (id)initWithURL:(NSURL*)unityURL;
- (void)UpdateURL:(NSURL*)unityURL;
- (bool)OpenDocument;
- (UIViewController *) documentInteractionControllerViewControllerForPreview: (UIDocumentInteractionController *) controller;
@end
@implementation DocumentHandler
- (id)initWithURL:(NSURL*)unityURL
{
self = [super init];
fileURL = unityURL;
return self;
}
- (void)UpdateURL:(NSURL*)unityURL {
fileURL = unityURL;
}
- (bool)OpenDocument {
UIDocumentInteractionController *interactionController =
[UIDocumentInteractionController interactionControllerWithURL: fileURL];
// Configure Document Interaction Controller
[interactionController setDelegate:self];
[interactionController presentPreviewAnimated:YES];
return true;
}
- (UIViewController *) documentInteractionControllerViewControllerForPreview: (UIDocumentInteractionController *) controller {
return UnityGetGLViewController();
}
@end
static DocumentHandler* docHandler = nil;
// Converts C style string to NSString
NSString* CreateNSString (const char* string)
{
if (string)
return [NSString stringWithUTF8String: string];
else
return [NSString stringWithUTF8String: ""];
}
extern "C" {
bool _OpenDocument (const char* path)
{
// Convert path to URL
NSString * stringPath = CreateNSString(path);
NSURL *unityURL = [NSURL fileURLWithPath:stringPath];
if (docHandler == nil)
docHandler = [[DocumentHandler alloc] initWithURL:unityURL];
else
[docHandler UpdateURL:unityURL];
[docHandler OpenDocument];
return true;
}
}

View File

@@ -0,0 +1,37 @@
fileFormatVersion: 2
guid: 93804f9d06962764c8ecf5d676d9c4e9
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
Any:
second:
enabled: 0
settings: {}
- first:
Editor: Editor
second:
enabled: 0
settings:
DefaultValueInitialized: true
- first:
iPhone: iOS
second:
enabled: 1
settings: {}
- first:
tvOS: tvOS
second:
enabled: 1
settings: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,12 @@
{
"name": "com.drstc.documenthandler",
"displayName": "DocumentHandler",
"version": "0.1.0",
"unity": "2019.4",
"description": "Open a document (e.g. .pfd) with a corresponding native app.",
"author": {
"name": "Draudastic",
"email": "via gitHub",
"url": "https://github.com/Draudastic26"
}
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: f84eb8099ddc06e4b83d7bb97b4710a2
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,153 @@
using System.Collections;
using System.Collections.Generic;
using drstc.DocumentHandler;
using UnityAndroidOpenUrl;
using UnityEngine;
public class MyFileOpen
{
public static void open(string path)
{
#if UNITY_ANDROID
AndroidOpenUrl.OpenFile(path);
#elif UNITY_IOS
DocumentHandler.OpenDocument(path);
#endif
}
public enum ImageFilterMode : int
{
Nearest = 0,
Biliner = 1,
Average = 2
}
public static Texture2D ResizeTexture(Texture2D pSource, int maxSize, ImageFilterMode pFilterMode = ImageFilterMode.Nearest)
{
//*** Variables
int i;
//*** Get All the source pixels
Color[] aSourceColor = pSource.GetPixels(0);
Vector2 vSourceSize = new Vector2(pSource.width, pSource.height);
//*** Calculate New Size
float ratex = 1.0f;
float ratey = 1.0f;
if (pSource.width > maxSize)
{
ratex = (float)maxSize / pSource.width;
}
if (pSource.height > maxSize)
{
ratey = (float)maxSize / pSource.height;
}
float rate = ratex > ratey ? ratey : ratex;
float xWidth = Mathf.RoundToInt((float)pSource.width * rate);
float xHeight = Mathf.RoundToInt((float)pSource.height * rate);
//*** Make New
Texture2D oNewTex = new Texture2D((int)xWidth, (int)xHeight, TextureFormat.RGBA32, false);
//*** Make destination array
int xLength = (int)xWidth * (int)xHeight;
Color[] aColor = new Color[xLength];
Vector2 vPixelSize = new Vector2(vSourceSize.x / xWidth, vSourceSize.y / xHeight);
//*** Loop through destination pixels and process
Vector2 vCenter = new Vector2();
for (i = 0; i < xLength; i++)
{
//*** Figure out x&y
float xX = (float)i % xWidth;
float xY = Mathf.Floor((float)i / xWidth);
//*** Calculate Center
vCenter.x = (xX / xWidth) * vSourceSize.x;
vCenter.y = (xY / xHeight) * vSourceSize.y;
//*** Do Based on mode
//*** Nearest neighbour (testing)
if (pFilterMode == ImageFilterMode.Nearest)
{
//*** Nearest neighbour (testing)
vCenter.x = Mathf.Round(vCenter.x);
vCenter.y = Mathf.Round(vCenter.y);
//*** Calculate source index
int xSourceIndex = (int)((vCenter.y * vSourceSize.x) + vCenter.x);
//*** Copy Pixel
aColor[i] = aSourceColor[xSourceIndex];
}
//*** Bilinear
else if (pFilterMode == ImageFilterMode.Biliner)
{
//*** Get Ratios
float xRatioX = vCenter.x - Mathf.Floor(vCenter.x);
float xRatioY = vCenter.y - Mathf.Floor(vCenter.y);
//*** Get Pixel index's
int xIndexTL = (int)((Mathf.Floor(vCenter.y) * vSourceSize.x) + Mathf.Floor(vCenter.x));
int xIndexTR = (int)((Mathf.Floor(vCenter.y) * vSourceSize.x) + Mathf.Ceil(vCenter.x));
int xIndexBL = (int)((Mathf.Ceil(vCenter.y) * vSourceSize.x) + Mathf.Floor(vCenter.x));
int xIndexBR = (int)((Mathf.Ceil(vCenter.y) * vSourceSize.x) + Mathf.Ceil(vCenter.x));
//*** Calculate Color
aColor[i] = Color.Lerp(
Color.Lerp(aSourceColor[xIndexTL], aSourceColor[xIndexTR], xRatioX),
Color.Lerp(aSourceColor[xIndexBL], aSourceColor[xIndexBR], xRatioX),
xRatioY
);
}
//*** Average
else if (pFilterMode == ImageFilterMode.Average)
{
//*** Calculate grid around point
int xXFrom = (int)Mathf.Max(Mathf.Floor(vCenter.x - (vPixelSize.x * 0.5f)), 0);
int xXTo = (int)Mathf.Min(Mathf.Ceil(vCenter.x + (vPixelSize.x * 0.5f)), vSourceSize.x);
int xYFrom = (int)Mathf.Max(Mathf.Floor(vCenter.y - (vPixelSize.y * 0.5f)), 0);
int xYTo = (int)Mathf.Min(Mathf.Ceil(vCenter.y + (vPixelSize.y * 0.5f)), vSourceSize.y);
//*** Loop and accumulate
Vector4 oColorTotal = new Vector4();
Color oColorTemp = new Color();
float xGridCount = 0;
for (int iy = xYFrom; iy < xYTo; iy++)
{
for (int ix = xXFrom; ix < xXTo; ix++)
{
//*** Get Color
oColorTemp += aSourceColor[(int)(((float)iy * vSourceSize.x) + ix)];
//*** Sum
xGridCount++;
}
}
//*** Average Color
aColor[i] = oColorTemp / (float)xGridCount;
}
}
//*** Set Pixels
oNewTex.SetPixels(aColor);
oNewTex.Apply();
//*** Return
return oNewTex;
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5ba2aac9cace44440952859a8a663fd3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: