Skip to content

Commit

Permalink
Ability to set backgroundColor of a image
Browse files Browse the repository at this point in the history
  • Loading branch information
dimonovdd committed Feb 14, 2021
1 parent 48444a5 commit def618e
Show file tree
Hide file tree
Showing 8 changed files with 52 additions and 25 deletions.
11 changes: 4 additions & 7 deletions ImageFromXamarinUI/ImageFromXamarinUI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,33 +13,30 @@
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<AssemblyFileVersion>1.0.0.0</AssemblyFileVersion>
<Version>1.0.0</Version>
<PackageVersion>1.0.0-pre1</PackageVersion>
<PackageVersion>1.0.0-pre2</PackageVersion>
<Authors>dimonovdd</Authors>
<Owners>dimonovdd</Owners>
<RepositoryUrl>https://github.com/dimonovdd/ImageFromXamarinUI</RepositoryUrl>
<PackageReleaseNotes>See: https://github.com/dimonovdd/ImageFromXamarinUI/releases</PackageReleaseNotes>
<DefineConstants>$(DefineConstants);</DefineConstants>
<UseFullSemVerForNuGet>false</UseFullSemVerForNuGet>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
<PackageProjectUrl>https://github.com/dimonovdd/ImageFromXamarinUI</PackageProjectUrl>
<DebugType>portable</DebugType>
<Configurations>Debug;Release</Configurations>
<Configurations>Debug;Release</Configurations>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)'=='Debug' ">
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DocumentationFile>bin\Debug\netstandard2.0\ImageFromXamarinUI.xml</DocumentationFile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DocumentationFile>bin\Release\netstandard2.0\ImageFromXamarinUI.xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<None Include="..\LICENSE" PackagePath="" Pack="true" />
<None Include="..\icon.png" PackagePath="" Pack="true" />
<PackageReference Include="Xamarin.Build.TypeRedirector" Version="0.1.2-preview" PrivateAssets="all" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
<PackageReference Include="Xamarin.Forms" Version="4.4.0.991864" />
<Compile Include="**\*.shared.cs" />
<Compile Include="**\*.shared.*.cs" />
Expand Down
8 changes: 4 additions & 4 deletions ImageFromXamarinUI/VisualElementExtension.android.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ namespace ImageFromXamarinUI
{
public static partial class VisualElementExtension
{
static async Task<Stream> PlatformCaptureImageAsync(VisualElement view)
static async Task<Stream> PlatformCaptureImageAsync(VisualElement view, Xamarin.Forms.Color backgroundColor)
{
using var bitmap = ViewToBitMap(GetNativeView(view));
using var bitmap = ViewToBitMap(GetNativeView(view), backgroundColor);
var stream = await BitMapToStream(bitmap);
bitmap.Recycle();
return stream;
Expand All @@ -27,11 +27,11 @@ static Android.Views.View GetNativeView(VisualElement view)
return render.View;
}

static Bitmap ViewToBitMap(Android.Views.View view)
static Bitmap ViewToBitMap(Android.Views.View view, Xamarin.Forms.Color backgroundColor)
{
var bitmap = Bitmap.CreateBitmap(view.Width, view.Height, Bitmap.Config.Argb8888);
using var canvas = new Canvas(bitmap);
canvas.DrawColor(Android.Graphics.Color.Transparent);
canvas.DrawColor(backgroundColor.ToAndroid());
view.Draw(canvas);

return bitmap;
Expand Down
20 changes: 15 additions & 5 deletions ImageFromXamarinUI/VisualElementExtension.ios.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.IO;
using System.Threading.Tasks;
using CoreGraphics;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
Expand All @@ -9,10 +10,10 @@ namespace ImageFromXamarinUI
{
public static partial class VisualElementExtension
{
static Task<Stream> PlatformCaptureImageAsync(VisualElement view)
static Task<Stream> PlatformCaptureImageAsync(VisualElement view, Color backgroundColor)
{
Stream stream = null;
using (var image = ViewToUIImage(GetNativeView(view)))
using (var image = ViewToUIImage(GetNativeView(view), backgroundColor))
stream = ImageToStream(image);
return Task.FromResult(stream);
}
Expand All @@ -27,10 +28,19 @@ static UIView GetNativeView(VisualElement view)
return render.NativeView;
}

static UIImage ViewToUIImage(UIView view)
static UIImage ViewToUIImage(UIView view, Color backgroundColor)
{
UIGraphics.BeginImageContextWithOptions(view.Frame.Size, false, UIScreen.MainScreen.Scale);
view.Layer.RenderInContext(UIGraphics.GetCurrentContext());
var size = view.Frame.Size;
UIGraphics.BeginImageContextWithOptions(size, false, UIScreen.MainScreen.Scale);
using var context = UIGraphics.GetCurrentContext();

if(backgroundColor != Color.Transparent)
{
context.SetFillColor(backgroundColor.ToCGColor());
context.FillRect(new CGRect(0, 0, size.Width, size.Height));
}

view.Layer.RenderInContext(context);
var image = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();

Expand Down
2 changes: 1 addition & 1 deletion ImageFromXamarinUI/VisualElementExtension.netstandard.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace ImageFromXamarinUI
{
public static partial class VisualElementExtension
{
static Task<Stream> PlatformCaptureImageAsync(VisualElement view)
static Task<Stream> PlatformCaptureImageAsync(VisualElement view, Color backgroundColor)
=> throw new NotImplementedException($"{nameof(CaptureImageAsync)} not supported on netstandart project");

}
Expand Down
6 changes: 4 additions & 2 deletions ImageFromXamarinUI/VisualElementExtension.shared.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@

namespace ImageFromXamarinUI
{
/// <summary>The extension class with methods for creating images</summary>
public static partial class VisualElementExtension
{
/// <summary>Captures an image from the current state of <paramref name="element"/></summary>
/// <param name="element">element to which the render was assigned</param>
/// <param name="backgroundColor"></param>
/// <returns>Stream an image as png with transparency</returns>
public static async Task<Stream> CaptureImageAsync(this VisualElement element)
=> await PlatformCaptureImageAsync(element);
public static async Task<Stream> CaptureImageAsync(this VisualElement element, Color? backgroundColor = null)
=> await PlatformCaptureImageAsync(element, backgroundColor ?? Color.Transparent);
}
}
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ async void OnCapture(Xamarin.Forms.VisualElement element)
{
try
{
var stream = await element.CaptureImageAsync();
var stream = await element.CaptureImageAsync(Color.White);
ResultImageSource = ImageSource.FromStream(() => stream);
}
catch (Exception)
Expand Down
9 changes: 6 additions & 3 deletions Sample/Sample/MainPage.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<sample:MainViewModel />
</ContentPage.BindingContext>
<ScrollView >
<StackLayout Background="Red" >
<StackLayout Background="Green" >
<Frame BackgroundColor="#2196F3" Padding="24" CornerRadius="0">
<Label Text="Welcome to Xamarin.Forms!" HorizontalTextAlignment="Center" TextColor="White" FontSize="36"/>
</Frame>
Expand All @@ -27,8 +27,11 @@
</Label.FormattedText>
</Label>

<Button Text="Capture" Background="#990000ff"
Command="{Binding CaptureCommand}" CommandParameter="{x:Reference rootView}"/>
<ContentView x:Name="button">
<Button Text="Capture" Background="#990000ff" Margin="10"
Command="{Binding CaptureCommand}" CommandParameter="{x:Reference button}"/>
</ContentView>


<Image Source="{Binding ResultImageSource}"/>

Expand Down
19 changes: 17 additions & 2 deletions Sample/Sample/MainViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System.Windows.Input;
using System.IO;
using System.Windows.Input;
using ImageFromXamarinUI;
using Xamarin.Essentials;
using Xamarin.Forms;

namespace Sample
Expand Down Expand Up @@ -27,8 +29,21 @@ public ImageSource ResultImageSource

async void OnCapture(VisualElement element)
{
var stream = await element.CaptureImageAsync();
var stream = await element.CaptureImageAsync(Color.Red.MultiplyAlpha(0.4));
ResultImageSource = ImageSource.FromStream(() => stream);


//var dir = FileSystem.CacheDirectory;
//var filepath = Path.Combine(dir, "image.jpg");

//if (File.Exists(filepath))
// File.Delete(filepath);

//var fileStream = File.OpenWrite(filepath);
//stream.CopyTo(fileStream);
//fileStream.Close();

//await Share.RequestAsync(new ShareFileRequest(new ShareFile(filepath)));
}
}
}

0 comments on commit def618e

Please sign in to comment.