Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all 77050 articles
Browse latest View live

TreeView in Xamarin Forms

$
0
0

As my subject,

I need to create a Treeview in Xamarin Forms.

Thanks a lot.


Xamarin Forms 1plus6 issue

$
0
0

Hi i have a Forms app running on Android, working fine apart from the specific device 1plus6 on version 9.0

When a click event occurs on this device "TapGestureRecognizer", the TranslateTo function does not work as expected, the below code moves the view about 5mm from the left, every other device is moving the view as expected.

await myView.TranslateTo(250, 60, 100);

Is this a known issue, are there any fixes for this?

How to get the IMEI number

$
0
0

Hello,

Is there a way to get the IMEI number from Xamarin Forms app?
for android and iOS.

forms App logs out in the background

$
0
0

Android restarts everytime on putting my Xamarin forms App to Background and bringing it back. This happens only in some devices( Zebra Scanning device TC75 EK android v 7.1.2) . This problem is not seen in other devices. Can someone help me with this. Thanks in advance.

Push or Pop ?

$
0
0

Hello,

Before accessing to Home page, I have a loading page. When some actions happen, i need to reload the app, and recall the loading page.
What is the best way to do it ?

Another push ? Stack will be very big if I do pushs in loop like that
Pop the page, and tell the loading page to restart the loading ? Best way to tell it is MessagingCenter ? OnDisappearing event ?

Does Application.Current.Properties support persistent storage?

$
0
0

I've seen various bits of information suggesting that Xamarin Forms 1.3 has built-in persistent property storage, however I've not been able to get any formal documentation, examples, or even confirmation that this is true in the first place.

So is that a capability, or not?

Thanks!

How do i refresh token background every time when it expires and i am not getting any refresh token?

$
0
0

after authentication i am getting only 4 properties in Xamarin.Auth.OAuth2Authenticator .
They are access token,token type,id token and expires in.
And what about authorized code and refresh token.

when i try to upload, it says The access token has expired but we can't refresh it.
Google OAuth2 - The access token has expired but we can't refresh it.

here is my code and help me out on refreshing a token

` authenticator
= new Xamarin.Auth.OAuth2Authenticator
(
clientId: "",
clientSecret: "", // null or ""
authorizeUrl: new Uri("https://accounts.google.com/o/oauth2/auth"), //Uri("https://accounts.google.com/o/oauth2/auth"),
accessTokenUrl: new Uri("https://www.googleapis.com/oauth2/v4/token"),
redirectUrl: new Uri("https://developers.google.com/oauthplayground"),
scope:
//"profile"
"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.login"
,
getUsernameAsync: null,
isUsingNativeUI: false
)
{
AllowCancel = true,
};
authenticator.Completed +=
(s, ea) =>
{
StringBuilder sb = new StringBuilder();
//var jsondata = ea.Account.Properties["id_token"];
//jsondata = JsonConvert.DeserializeObject(jsondata);
if (ea.Account != null && ea.Account.Properties != null)
{
sb.Append("Token = ").AppendLine($"{ea.Account.Properties["access_token"]}");
DependencyService.Get<IToken>().SaveTokenData(ea.Account);
App.Current.MainPage = new FilesList();
}
else
{
sb.Append("Not authenticated ").AppendLine($"Account.Properties does not exist");
}

                DisplayAlert
                        (
                            "Authentication Results",
                            sb.ToString(),
                            "OK"
                        );

                return;
            };

        authenticator.Error +=
            (s, ea) =>
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("Error = ").AppendLine($"{ea.Message}");

                DisplayAlert
                        (
                            "Authentication Error",
                            sb.ToString(),
                            "OK"
                        );
                return;
            };


        // after initialization (creation and event subscribing) exposing local object 
        AuthenticationState.Authenticator = authenticator;

        await Screen(authenticator);

        return;`

Hybrid Webview Windows UWP crash webOnNavigating with long URL

$
0
0

We have a UWP App using a Hybrid Webview which started to crash a few days ago.
We traced it down to a line of JavaScript inside the HTML page to Call a C#-Method in the underlying CS-Code.
This call causes the UWP to crash and disappear without further notifcation, even if running from withing visual studio. It seems to be related to the length of the URL created to navigate to (storage is the JSON-Data to pass to SetStorageAsync):
location.replace(HYBRID_URL + "SetStorageAsync" + "?" + "data=" + storage);

Windows Event Log:
Name des fehlerhaften Moduls: edgehtml.dll, Version: 11.0.17763.437, Zeitstempel: 0xb1870ea7
Ausnahmecode: 0x80004003
Fehleroffset: 0x00000000008a14f5
ID des fehlerhaften Prozesses: 0x6aec
Startzeit der fehlerhaften Anwendung: 0x01d4f4fafe9b1c59

Windows Version:

Did MS change something related to this (I guess it is the Edge URL length) in last Windows Updates?

Stephan


Custom DatePicker and TimePicker (combined) Recipe

$
0
0

Hi guys, I just wanted to share a custom render for an extended DatePicker. This way, users will be able to select Date and Time in a single control. You can also select the time interval, in my case I needed 15 minutes intervals. It took me a while to sort it out, so hopefully it will save you some time.

This is only for iOS, but will post Droid when I get there. Xamarin team should include this control in future versions.

Note: DatePicker will only show the date, with no time. You need to display the value in a separate Label.

Xamarin Forms:

public class CustomDateTimePicker : DatePicker
    {
        private DateTime cdt;
        public event EventHandler<DateTimePickerArgs> DTChanged;
        public DateTime CDT
        {
            get { return cdt; }
            set
            {
                cdt = this.Date = value;
                if (DTChanged != null)
                    DTChanged.Invoke(this, new DateTimePickerArgs(cdt));
            }
        }
    }

    public class DateTimePickerArgs : EventArgs
    {
        private DateTime dt;
        public DateTimePickerArgs(DateTime NewDT)
        {
            dt = NewDT;
        }
        public DateTime DT { get { return dt; } }
    }

Xamarin iOS Custom Render

                    [assembly: ExportRenderer(typeof(CustomDateTimePicker), typeof(CustomDateTimePickerRenderer))]

                    namespace ProjectX.iOS.CustomRenderers
                    {
                        public class CustomDateTimePickerRenderer : DatePickerRenderer
                        {
                            public CustomDateTimePicker dtPicker;
                            protected override void OnElementChanged(ElementChangedEventArgs<DatePicker> e)
                            {
                                base.OnElementChanged(e);

                                dtPicker = e.NewElement as CustomDateTimePicker;

                                if (Control!=null)
                                {
                                    var input = Control.InputView as UIDatePicker;
                                    if (input != null && input.Mode != UIDatePickerMode.DateAndTime)
                                    {
                                        input.Mode = UIDatePickerMode.DateAndTime;
                                        input.MinuteInterval = 15;//TODO CHECK
                                        input.ValueChanged += Input_ValueChanged;
                                    }
                                }
                            }
                            private void Input_ValueChanged(object sender, EventArgs e)
                            {
                                if (Control != null)
                                {
                                    var input = sender as UIDatePicker;

                                    if (dtPicker != null)
                                    {
                                        dtPicker.CDT = input.Date.ToDateTime();
                                    }

                                }

                            }
                        }
                    }

Usage
XAML

          <extended:CustomDateTimePicker x:Name="pckDate" 
                  Grid.Row="0" Grid.RowSpan="2" 
                  BackgroundColor="Transparent" 
                  TextColor="Black" IsVisible="False"
                  HorizontalOptions="Center"
                  VerticalOptions="Center"
                  Format="dddd, dd MMMM hh:mm tt"
                  />

Event wireup
pckDate.DTChanged += PckDate_DTChanged;

To make it visible (since its always invisible)

        private void Schedule_Tapped(object sender, EventArgs e)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                pckDate.Focus();
            });
        }

Extras (In AppDelegate):
UIDatePicker.Appearance.BackgroundColor = bgColor;
UIDatePicker.Appearance.TintColor = textColor;

Camera Plugin.Media.Abstractions.StoreCameraMediaOptions always rotated landscape

$
0
0

var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
SaveToAlbum = true,
SaveMetaData = true,
Directory = "",
MaxWidthHeight = 1500,
CompressionQuality = 75,
PhotoSize = PhotoSize.Medium,
RotateImage = false,
});
when camera open , it's alway rotated landscape , phone & simulator set Portrait . Have StoreCameraMediaOptions any thing can set this issue ???
AND,
After take photo , can't resize image, i try use BitmapFactory to resize, but not working.

Have any thing can resolve 2 issue above , please tell me.
Thanks So much.

BindableLayout does not work with ObservableCollection?

$
0
0

I am trying to bind a StackLayout according to this documentation but I find that when my collection changes, the changes are not visible in my bound StackLayout. If I replace the StackLayout with a ListView everything works fine. Is this a known limitation/issue in BindableLayouts?

Thinking of getting a new Macbook Pro to have better build times

$
0
0

Hi guys,

I am really fed up with long build times Xamarin.Forms has!

I am currently using a Macbook Pro Early 2011 with 16GB of RAM, 256GB SSD, 2.2 GHz Core i7 Quad Core processor but it takes ages to build a relatively simple app not to mention building in release mode using LLVM that could take up to 15-30 minutes!

On that note, I am considering to get a new Macbook Pro 2018 Core i9 6-core 32GB of RAM and 2TB SSD. When maxing out the CPU and GPU, the price comes to a whopping £4600 (I can of course claim the 20% VAT back) but before doing so, I was wondering if anyone has had a similar experience of building with a high end machine like the one I mentioned above and whether it's worth it or not.

Also, does anyone know if there is a way to boost build times using the GPU power?

Thanks!

How to deserialize and get into model class nested Json ?

$
0
0

This I the json string {"usermachine":[{"employeeid":"EMP002 ","employeename":"EMP002 NAME","machineid":"E0138","machinename":"FOS","iscleaning":1,"isperforming":1,"isverifying":1},{"cInterval":112,"cCleanOperationMaxTime":86400,"cPerformOperationMaxTime":300},{"oSequenceID":2,"oCompletedOperation":1,"oComplOperStartTime":1555384452,"oCompOperEndndTime":1555384652,"oOperationToContinue":2},{"pinterval":[{"pLocationNumber":1,"pLocationName":"TestLoc1","pLocationInterval":12},{"pLocationNumber":2,"pLocationName":"TestLoc2","pLocationInterval":1121}]}]}

Json2Csharp class
public class Pinterval
{
public int pLocationNumber { get; set; }
public string pLocationName { get; set; }
public int pLocationInterval { get; set; }
}

public class Usermachine
{
public string employeeid { get; set; }
public string employeename { get; set; }
public string machineid { get; set; }
public string machinename { get; set; }
public int iscleaning { get; set; }
public int isperforming { get; set; }
public int isverifying { get; set; }
public int? cInterval { get; set; }
public int? cCleanOperationMaxTime { get; set; }
public int? cPerformOperationMaxTime { get; set; }
public int? oSequenceID { get; set; }
public int? oCompletedOperation { get; set; }
public int? oComplOperStartTime { get; set; }
public int? oCompOperEndndTime { get; set; }
public int? oOperationToContinue { get; set; }
public List pinterval { get; set; }
}

public class RootObject
{
public List usermachine { get; set; }
}

This is my models.class
public class Pinterval
{
public int pLocationNumber { get; set; }
public string pLocationName { get; set; }
public int pLocationInterval { get; set; }
}

public class Usermachine
{
    public string employeeid { get; set; }
    public string employeename { get; set; }
    public string machineid { get; set; }
    public string machinename { get; set; }
    public int iscleaning { get; set; }
    public int isperforming { get; set; }
    public int isverifying { get; set; }
    public int cInterval { get; set; }
    public int cCleanOperationMaxTime { get; set; }
    public int cPerformOperationMaxTime { get; set; }
    public int oSequenceID { get; set; }
    public int oCompletedOperation { get; set; }
    public int oComplOperStartTime { get; set; }
    public int oCompOperEndndTime { get; set; }
    public int oOperationToContinue { get; set; }
    public List<Pinterval> pinterval { get; set; }

}

public class UsermachineList
{
    public List<Usermachine> usermachine { get; set; }
}

My Code to retrieve data works with the Usermachine structure but not with the pinterval list.
my code :
var client = new System.Net.Http.HttpClient();

            var response = await client.GetAsync(linkremoved as I am getting a message you have to be around for a while);
            string usersJson = await response.Content.ReadAsStringAsync();
            UsermachineList objUsermachineList = new UsermachineList();
            if (usersJson != "")
            {
                //Converting JSON Array Objects into generic list  
                objUsermachineList = JsonConvert.DeserializeObject<UsermachineList>(usersJson);
                //partially original changed products to productsJason
                // objProductList = JsonConvert.DeserializeAnonymousType(productsJason);
                //// var prds = JsonConvert.DeserializeObject(productsJason);

            }
            //Binding listview with server response    

           // listviewProducts.ItemsSource = objUsermachineList.usermachine;
            foreach (var usm in objUsermachineList.usermachine)
            {
                if (usm != null)
                {
                    string data2Display = usm.employeename.ToString() + " / " + usm.employeeid.ToString() + " / " + usm.machinename.ToString();
                    string pintDisplay = "";
                    foreach (var pint in usm.pinterval) // *** This is where I get issues. pinterval is null
                    {
                        if (pint != null)
                        {
                            pintDisplay = pint.pLocationInterval.ToString() + " / " + pint.pLocationName.ToString() + " / " + pint.pLocationInterval.ToString();

                        }
                        else
                        {
                            break;
                        }
                    }
                    await DisplayAlert("UserMachine", data2Display, "OK");
                    await DisplayAlert("Interval", pintDisplay, "OK");

Hope someone can throw some light and share your ideas.
Thanks in advance

How to Attach Debugger to a Running Android or IOS app?

$
0
0

I often start an app just to see how it works, then I decide to debug, so I just attach to its process and debugging kicks in.

But I am not able to find how to attach to a running Xamarin Forms app process to start debugging.

To clarify, I know how to debug and that works fine but how do I attach debugger to a running Xamarin Forms app to debug?

How to update list of online users

$
0
0

Heyo, newbie to Xamarin.Forms, and among all my searching I cannot seem to find an answer to this (seemingly) simple question... How do I show a list of online users of my service, and update that list as users log on and off? The scenario I am trying to accomplish is that the user is sitting on the page that shows the list of users currently online, and I would like to see this binding updated dynamically as other users log on and off (i.e., the user sees names being added to and removed from the page).

For the details of my implementation...

When my user logs into my app, a signalR connection is made which passes back a list of other users who are online. This list is stored as a static variable that is defined in App.xaml.cs and is used to populate an ObservableCollection called UsersOnlineList that is then bound to my ListView.

ChatUser.cs

    public class ChatUser
    {
        public int UserId {get; set;}
        public string UserName { get; set; }

        public ChatUser()
        {

        }
    }

App.xaml.cs

public static List<ChatUser> ConnectedUsers { get; set; }

GroupedList.cs

    public class GroupedList: List<ChatUser>
    {
        public string GroupHeader { get; set; }
        public List<ChatUser> Users => this;
    }

UsersOnlineViewModel.cs

        public ObservableCollection<GroupedList> UsersOnlineList { get; set; }

UsersOnlinePage.xaml

<ContentPage.Content>
        <StackLayout>
            <ListView x:Name="MyListView" 
                ItemsSource="{Binding UsersOnlineList}"
                      IsGroupingEnabled="True"
                VerticalOptions="FillAndExpand"
                 HasUnevenRows="true"
                      RefreshCommand="{Binding LoadUsersCommand}"
                      IsPullToRefreshEnabled="true"
                      IsRefreshing="{Binding IsBusy, Mode=TwoWay}"
                 CachingStrategy="RecycleElement"
                 ItemSelected="OnItemSelected">
                <ListView.GroupHeaderTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Label Text="{Binding GroupHeader}" />
                        </ViewCell>
                    </DataTemplate>
                </ListView.GroupHeaderTemplate>
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <StackLayout Padding="10">
                                <Label Text="{Binding UserName}" 
                       LineBreakMode="NoWrap" 
                       Style="{DynamicResource ListItemTextStyle}" 
                       FontSize="16" />
                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ContentPage.Content>

FYI, the reason I am going from the "global" App.ConnectedUsers List to the ObservableCollection is so that I can define a heading for grouping purpose, as well as do a little re-organization of the list of online users before it is displayed in the app.

If another user logs on or off, a signalR call will be sent to all connected clients denoting the user that logged on or off.

HubManager.cs

            AppHubProxy.On<ChatUser>("onUserDisconnected", (cu) =>
            {
                int cuIdx = App.ConnectedUsers.FindIndex(obj => obj.UserId == cu.UserId);
                if (cuIdx > -1)
                {
                    App.ConnectedUsers.RemoveAt(cuIdx);
                }
            });

What I am missing is how do I go from the onUserDisconnected callback occurring to updating the UsersOnlineList that binds to the ListView?

As a newbie, I am 100% open to different implementations that accomplish what I am trying to do more efficiently

Thank you in advance!


How can I create and auto-start a service app, just after installation without launching it?

$
0
0

I want to create and auto-start a background service app just after it is installed from the play store, without launching it. The purpose to the service app is to initialise a centralised local database that needs to be accessed and modify by two other Xamarin apps. How can I achieve this?

Custom Renderer for Span

$
0
0

Hello devs!

I'm trying to make a Custom Renderer to ignore the ****android**** accessibility configurations in the ****Span Class****, to ****not re-scale the font size****.
I have made successfully renderer for the Label class but not for Span class.. Can someone help me? :D

****My Label Custom Renderer is Above!****
<br /> using System;<br /> using System.ComponentModel;<br /> using Android.Widget;<br /> using FreePlay.Droid;<br /> using Xamarin.Forms;<br /> using Xamarin.Forms.Platform.Android;</p> <p>[assembly: ExportRenderer(typeof(Span), typeof(IgnoreAcessibilitySpan))]<br /> namespace FreePlay.Droid<br /> {</p> <pre><code>public class IgnoreAcessibilitySpan : LabelRenderer { protected void setFontSizeAgain() { var nativeControl = (TextView)Control; var xfControl = Element; //e.NewElement; if (nativeControl != null && xfControl != null) nativeControl.SetTextSize(Android.Util.ComplexUnitType.Dip, xfControl.Font.ToScaledPixel()); } protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Label> e) { base.OnElementChanged(e); setFontSizeAgain(); } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); setFontSizeAgain(); } }

}

SkiaSharp Modify and save existing bitmap

$
0
0

I am trying to take an existing fingerpaint bitmap which is loaded onto the canvas, modify it by adding fingerpainting to it, and then save the modified bitmap. When I reload the newly saved bitmap it comes up as all black. Can anyone help?

    void SaveSketchToFile_EventHandler(object sender, EventArgs e)
    {

        // find and delete any existing file from local database
        IEnumerable<DocumentFile> binarySketches = App.database.GetSketches(sampleStationPassed.SampleStationLocalGuid);

        foreach(DocumentFile sketch in binarySketches)
        {
            App.Database.DeleteImageFromDatabase(sketch, sampleStationPassed.SampleStationLocalGuid);
        }


        // and now save what is on the canvas....


        // create non-visible surface in memory
        var info = new SKImageInfo((int)canvasView.CanvasSize.Width, (int)canvasView.CanvasSize.Height, SKImageInfo.PlatformColorType, SKAlphaType.Premul);
        var surface = SKSurface.Create(info);


        if(bitmapSketch != null)
        {
            using (var existingCanvas = new SKCanvas(bitmapSketch))
            {

                existingCanvas.Clear(SKColors.White);

                // draw original bitmap
                // Draw original in full size
                float x = (info.Width - bitmapSketch.Width) / 2;
                float y = (info.Height - bitmapSketch.Height) / 2;
                existingCanvas.DrawBitmap(bitmapSketch, x,y);


                // redraw objects on non-visible surface 
                foreach (PathAndSpecs pathSpecs in completedPathsWithSpecs)
                {
                    existingCanvas.DrawPath(pathSpecs.path, pathSpecs.paint);
                }

                foreach (PathAndSpecs pathSpecs in inProgressPathsWithSpecs.Values)
                {
                    existingCanvas.DrawPath(pathSpecs.path, pathSpecs.paint);
                }


                existingCanvas.Flush();

            }

        }
        else
        {
            using (var canvas = surface.Canvas)
            {

                canvas.Clear(SKColors.White);

                // redraw objects on noni ble surface 
                foreach (PathAndSpecs pathSpecs in completedPathsWithSpecs)
                {
                    canvas.DrawPath(pathSpecs.path, pathSpecs.paint);
                }

                foreach (PathAndSpecs pathSpecs in inProgressPathsWithSpecs.Values)
                {
                    canvas.DrawPath(pathSpecs.path, pathSpecs.paint);
                }

                canvas.Flush();
            }


        }

        canvasView.InvalidateSurface();

        // take a snapshot of the surface and return as an image
        var snap = surface.Snapshot();

        // encode the image as a certain file type or convert to byte array for storage
        SKData jpgImage = snap.Encode(SKEncodedImageFormat.Jpeg, 100);

        // convert image to byte array
        byte[] jpgByteArray = jpgImage.ToArray();


        // save image as jpg to local database where it will be stored for upload.
        CreateAndSavePic(jpgByteArray, "Site Sketch");



    }




    private void CreateAndSavePic(byte[] dbPhoto, string documentType)
    {

        DocumentSet docset = App.Database.PhotoDocumentSetExists(sampleStationPassed.SampleStationLocalGuid, documentType);

        if (docset is null) // create new documentSet for pics
        {
            // create new document set locally and update properties
            docset = new DocumentSet()
            {
                DocumentSetLocalGUID = DependencyService.Get<IDeviceMethods>().GUIDGenerator(),
                DeviceInfoID = App.deviceInfoID,
                DocumentSetObjectLocalGUID = sampleStationPassed.SampleStationLocalGuid,
                DocumentType = documentType,
                DocumentSetObject = "SampleStation",
                DocumentSetObjectID = sampleStationPassed.SampleStationID
                //Description = "Site images for this station visit_" + System.DateTime.Now.ToString() + "_" + sampleStationView.StationName

            };

            // save new photo to local database
            App.Database.SaveNewDocumentSet(docset);

        }


        DocumentFile newPhoto = new DocumentFile
        {
            BinaryObject = dbPhoto,

            // should be new one every time
            DocumentFileLocalGUID = DependencyService.Get<IDeviceMethods>().GUIDGenerator(),
            FileName = System.DateTime.Now.ToString() + "_Image",
            FileStorageType = "SQL Binary",
            FileType = "Portable Network Graphic",
            // DeviceInfoID = Convert.ToInt32(App.deviceInfoID),
            DocumentSetID = docset.DocumentSetID,
            DocumentSetLocalGUID = docset.DocumentSetLocalGUID

        };

        // save new photo to local database
        App.Database.SaveNewPhoto(newPhoto);

    }

Unexpected behavior when selecting listview items with changed background color only on iOS

$
0
0

Dear all,

I'm currently developing an app with Xamarin.Forms where i got an very strange behavior when I select listview items.
One feature of this app should be a view cell with a non default background color when selected.

I tried many ways (*not tested on a real apple device): dataTriggers, stackLayout with backgroundColor binding, custom viewCells

The last one successed on android but on iOS the following is happening:
Example: 3 Items ('1', '2', '3')

Select: 1

  • Nothing happens
  • Select: 3

  • 1 Selected

Select: 2

  • 3 Selected

so on .....

Code:

  [assembly: ExportRenderer(typeof(ExtendedViewCell), typeof(ExtendedViewCellRenderer))]
  namespace IOS
  public class ExtendedViewCellRenderer : ViewCellRenderer
  {
       public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
       {
            var cell = base.GetCell(item, reusableCell, tv);
            var view = item as ExtendedViewCell;
            cell.SelectedBackgroundView = new UIView
            {
                    BackgroundColor = view.SelectedBackgroundColor.ToUIColor(),
             };

           return cell;
      } 


 [assembly: ExportRenderer(typeof(ExtendedViewCell), typeof(ExtendedViewCellRenderer))]
 namespace Android
 {
   public class ExtendedViewCellRenderer : ViewCellRenderer
   {

     private Android.Views.View _cellCore;
     private Drawable _unselectedBackground;
     private bool _selected;

     protected override Android.Views.View GetCellCore(Cell item, Android.Views.View convertView, ViewGroup parent, Context context)
     {
       _cellCore = base.GetCellCore(item, convertView, parent, context);
       _selected = false;
       _unselectedBackground = _cellCore.Background;
       return _cellCore;
     }

     protected override void OnCellPropertyChanged(object sender, PropertyChangedEventArgs args)
     {
       base.OnCellPropertyChanged(sender, args);

       if (args.PropertyName == "IsSelected")
       {
         _selected = !_selected;

         if (_selected)
         {
              var extendedViewCell = sender as ExtendedViewCell;
             _cellCore.SetBackgroundColor(extendedViewCell.SelectedBackgroundColor.ToAndroid());
         }
        else            _cellCore.SetBackground(_unselectedBackground);
       }
     }
   }
}


public class ExtendedViewCell : ViewCell
{
        public static readonly BindableProperty SelectedBackgroundColorProperty = BindableProperty.Create("SelectedBackgroundColor", typeof(Color), typeof(ExtendedViewCell), Color.Default);

    public Color SelectedBackgroundColor
        {
            get { return (Color)GetValue(SelectedBackgroundColorProperty); }
            set { SetValue(SelectedBackgroundColorProperty, value); }
        }
}

<ListView VerticalOptions="FillAndExpand"  HorizontalOptions="FillAndExpand"  BackgroundColor="Black"  ItemsSource="{Binding .}" RowHeight="52">
<ListView.ItemTemplate>
            <DataTemplate>
                <customControls:ExtendedViewCell SelectedBackgroundColor="Teal">
          <ViewCell.View>
            <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Orientation="Vertical" Padding="4" Spacing="8">
                <Label TextColor="White" Text="{Binding Name}"/>
            </StackLayout>
          </ViewCell.View>
        </customControls:ExtendedViewCell>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>

BindingContext = public ObservableCollection<Model> MyModels { get; set; }

Does anyone know whats wrong here?

All nuget versions are up to date.
Tried on iPhone 6s Plus, iPhone 8 Plus (Simulator).

Thank you

SkiaSharp Modify and save existing bitmap

$
0
0

I am trying to take an existing fingerpaint bitmap which is loaded onto the canvas, modify it by adding fingerpainting to it, and then save the modified bitmap. When I reload the newly saved bitmap it comes up as all black. Can anyone help?

    void SaveSketchToFile_EventHandler(object sender, EventArgs e)
    {

        // find and delete any existing file from local database
        IEnumerable<DocumentFile> binarySketches = App.database.GetSketches(sampleStationPassed.SampleStationLocalGuid);

        foreach(DocumentFile sketch in binarySketches)
        {
            App.Database.DeleteImageFromDatabase(sketch, sampleStationPassed.SampleStationLocalGuid);
        }


        // and now save what is on the canvas....


        // create non-visible surface in memory
        var info = new SKImageInfo((int)canvasView.CanvasSize.Width, (int)canvasView.CanvasSize.Height, SKImageInfo.PlatformColorType, SKAlphaType.Premul);
        var surface = SKSurface.Create(info);


        if(bitmapSketch != null)
        {
            using (var existingCanvas = new SKCanvas(bitmapSketch))
            {

                existingCanvas.Clear(SKColors.White);

                // draw original bitmap
                // Draw original in full size
                float x = (info.Width - bitmapSketch.Width) / 2;
                float y = (info.Height - bitmapSketch.Height) / 2;
                existingCanvas.DrawBitmap(bitmapSketch, x,y);


                // redraw objects on non-visible surface 
                foreach (PathAndSpecs pathSpecs in completedPathsWithSpecs)
                {
                    existingCanvas.DrawPath(pathSpecs.path, pathSpecs.paint);
                }

                foreach (PathAndSpecs pathSpecs in inProgressPathsWithSpecs.Values)
                {
                    existingCanvas.DrawPath(pathSpecs.path, pathSpecs.paint);
                }


                existingCanvas.Flush();

            }

        }
        else
        {
            using (var canvas = surface.Canvas)
            {

                canvas.Clear(SKColors.White);

                // redraw objects on noni ble surface 
                foreach (PathAndSpecs pathSpecs in completedPathsWithSpecs)
                {
                    canvas.DrawPath(pathSpecs.path, pathSpecs.paint);
                }

                foreach (PathAndSpecs pathSpecs in inProgressPathsWithSpecs.Values)
                {
                    canvas.DrawPath(pathSpecs.path, pathSpecs.paint);
                }

                canvas.Flush();
            }


        }

        canvasView.InvalidateSurface();

        // take a snapshot of the surface and return as an image
        var snap = surface.Snapshot();

        // encode the image as a certain file type or convert to byte array for storage
        SKData jpgImage = snap.Encode(SKEncodedImageFormat.Jpeg, 100);

        // convert image to byte array
        byte[] jpgByteArray = jpgImage.ToArray();


        // save image as jpg to local database where it will be stored for upload.
        CreateAndSavePic(jpgByteArray, "Site Sketch");



    }




    private void CreateAndSavePic(byte[] dbPhoto, string documentType)
    {

        DocumentSet docset = App.Database.PhotoDocumentSetExists(sampleStationPassed.SampleStationLocalGuid, documentType);

        if (docset is null) // create new documentSet for pics
        {
            // create new document set locally and update properties
            docset = new DocumentSet()
            {
                DocumentSetLocalGUID = DependencyService.Get<IDeviceMethods>().GUIDGenerator(),
                DeviceInfoID = App.deviceInfoID,
                DocumentSetObjectLocalGUID = sampleStationPassed.SampleStationLocalGuid,
                DocumentType = documentType,
                DocumentSetObject = "SampleStation",
                DocumentSetObjectID = sampleStationPassed.SampleStationID
                //Description = "Site images for this station visit_" + System.DateTime.Now.ToString() + "_" + sampleStationView.StationName

            };

            // save new photo to local database
            App.Database.SaveNewDocumentSet(docset);

        }


        DocumentFile newPhoto = new DocumentFile
        {
            BinaryObject = dbPhoto,

            // should be new one every time
            DocumentFileLocalGUID = DependencyService.Get<IDeviceMethods>().GUIDGenerator(),
            FileName = System.DateTime.Now.ToString() + "_Image",
            FileStorageType = "SQL Binary",
            FileType = "Portable Network Graphic",
            // DeviceInfoID = Convert.ToInt32(App.deviceInfoID),
            DocumentSetID = docset.DocumentSetID,
            DocumentSetLocalGUID = docset.DocumentSetLocalGUID

        };

        // save new photo to local database
        App.Database.SaveNewPhoto(newPhoto);

    }
Viewing all 77050 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>