Geen omschrijving
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ApplyCircleMask.cs 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using UnityEngine;
  2. namespace Unity.PlasticSCM.Editor.UI.Avatar
  3. {
  4. internal static class ApplyCircleMask
  5. {
  6. internal static Texture2D For(Texture2D sourceImage)
  7. {
  8. int centerx = sourceImage.width / 2;
  9. int centery = sourceImage.height / 2;
  10. int radius = sourceImage.width / 2;
  11. Texture2D result = Images.GetNewTextureFromTexture(sourceImage);
  12. for (int i = (centerx - radius); i < centerx + radius; i++)
  13. {
  14. for (int j = (centery - radius); j < centery + radius; j++)
  15. {
  16. float dx = i - centerx;
  17. float dy = j - centery;
  18. float d = Mathf.Sqrt(dx * dx + dy * dy);
  19. float borderSize = 1f;
  20. if (d <= (radius - borderSize))
  21. {
  22. result.SetPixel(
  23. i - (centerx - radius),
  24. j - (centery - radius),
  25. sourceImage.GetPixel(i, j));
  26. continue;
  27. }
  28. Color color = sourceImage.GetPixel(i, j);
  29. result.SetPixel(
  30. i - (centerx - radius),
  31. j - (centery - radius),
  32. Color.Lerp(Color.clear, color,
  33. GetAntialiasAlpha(radius, d, borderSize)));
  34. }
  35. }
  36. result.Apply();
  37. return result;
  38. }
  39. static float GetAntialiasAlpha(float radius, float d, float borderSize)
  40. {
  41. if (d >= (radius + borderSize))
  42. return 0f;
  43. if (d - radius - borderSize == 0)
  44. return 0;
  45. float proportion =
  46. Mathf.Abs(d - radius - borderSize) /
  47. (radius + borderSize) - (radius - borderSize);
  48. return Mathf.Max(0, 1.0f - proportion);
  49. }
  50. }
  51. }