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

How to save a SkiaSharp drawing?

$
0
0

I must be missing something. I started with the FingerPainting part of the TouchTrackingEffectDemos. After drawing something, I want to save it so I added a Save Button (just like there is a Clear Button). The Save button is supposed to save the drawing to my device but all I get is a blank white jpg. I am using Snapshot to capture the image. I suspect that it is not working the way I expect.
Here is my code for the Save. Any insight into how to save the drawing to a file is much appreciated!

`
void OnSaveButtonClicked(object sender, EventArgs args)
{
int width = (int)canvasView.CanvasSize.Width;
int height = (int)canvasView.CanvasSize.Height;
var info = new SKImageInfo(width, height);

        var item = (FingerPaintPage)((Button)sender).BindingContext;

        using (var surface = SKSurface.Create(width, height, SKImageInfo.PlatformColorType, SKAlphaType.Premul))
        {
            SKData skData = surface.Snapshot().Encode();

            IFolder folder = FileSystem.Current.LocalStorage;
            string path = folder.Path;
            string fileout = path + "/outfile.jpg";
            string fileout2 = path + "/outfile2.jpg";

            // Plan A)
            using (Stream stream2 = File.OpenWrite(fileout))
            {
                skData.SaveTo(stream2);
            }        

            // Plan B)
            SKBitmap bitmap = new SKBitmap(width, height);
            // create an image and then get the PNG (or any other) encoded data
            using (var image = SKImage.FromBitmap(bitmap))
            using (var data = image.Encode(SKEncodedImageFormat.Jpeg, 100))
            {
                // save the data to a stream
                using (var stream = File.OpenWrite(fileout2))
                {
                    data.SaveTo(stream);
                }
            }
        }
    }`

Not able to set the GOOGLE_APPLICATION_CREDENTIALS environment variable for Google.Cloud.Translation

$
0
0

I'm trying to use Google.Cloud.Translation for the translation of text in xamarin forms. I enabled the API. Created a json file from the Service account. Followed the step in the following url https://cloud.google.com/translate/docs/setup

But still when I try to set the GOOGLE_APPLICATION_CREDENTIALS I get exception-

Error reading credential file from location C:/Users/xxx/Downloads/xxxx-280817-bedb566bfd11.json: Could not find a part of the path "/C:/Users/xxxx/Downloads/xxxx-280817-bedb566bfd11.json". Please check the value of the Environment Variable GOOGLE_APPLICATION_CREDENTIALS

I have tried numerous ways to fix this. This is my code

System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS","C:/Users/xxx/Downloads/xx-280817-bedb566bfd11.json");

                TranslationClient client = TranslationClient.Create();

I have no clue how to fix this. Any suggestions?

How to create a Multiple Choice quiz based on a True/False quiz?

$
0
0

Hi. I have the code for a True/False quiz app, and I'd like to modify it in order to have a "multiple choice" (4 options) section. For the T/F component, I used a boolean to check whether the answer was T or F. However, how can I expand on this so I have 4 options to choose from instead of 2? Would I even use bool for this task? Thanks!

Question.cs (Model)

public string QuestionText { get; set; }
public bool Answer { get; set; }
public string AnswerCR { get; set; }

QuizViewModel

public event PropertyChangedEventHandler PropertyChanged;

    void OnPropertyChanged([CallerMemberName] string name = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }

    public List<Question> questions;

    public List<Question> errors = new List<Question>();


    private string _textquestion;

    public string TextQuestion
    {
        get
        {
            return _textquestion;
        }

        set
        {
          _textquestion = value;
            OnPropertyChanged();
        }
    }

    private bool _currentAnswerValue;
    public bool CurrentAnswerValue
    {
        get
        {
            return _currentAnswerValue;
        }

        set
        {
            _currentAnswerValue = value;
            OnPropertyChanged();
        }
    }

    private int _totalQuestions;
    public int TotalQuestions
    {
        get
        {
            return _totalQuestions;
        }

        set
        {
            _totalQuestions = value;
            OnPropertyChanged();
            OnPropertyChanged(nameof(TitleText));
        }
    }

    private int _currentQuestionNumber;
    public int CurrentQuestionNumber
    {
        get
        {
            return _currentQuestionNumber;
        }

        set
        {
            _currentQuestionNumber = value;
            OnPropertyChanged();
            OnPropertyChanged(nameof(TitleText));
        }
    }

    public string TitleText
    {
        get { return $"Question {_currentQuestionNumber} of {_totalQuestions}"; }
    }

    private int score;

    private Random random;

    public Command AnsweredTrue { get; }
    public Command AnsweredFalse { get; }
    public string QuestionText { get; }

    public QuizViewModel()
    {
        // initialise RNG
        random = new Random();

        // populate question list - replace with external data source in production
        questions = new List<Question>()
        {
            new Question() { QuestionText="", Answer=false } ,
            new Question() { QuestionText="", Answer=false },
            new Question() { QuestionText="", Answer=true },
            new Question() { QuestionText="", Answer=false },
            new Question() { QuestionText="" , Answer=true },
            new Question() { QuestionText="", Answer=false },
            new Question() { QuestionText="", Answer=false },
            new Question() { QuestionText="", Answer=false },
            new Question() { QuestionText="", Answer=false },
            new Question() { QuestionText="", Answer=true },
            new Question() { QuestionText="", Answer=false },

        };

        // initialise quiz values
        TotalQuestions = questions.Count;
        CurrentQuestionNumber = 1;
        score = 0;

        // load first question
        LoadQuestion();



        //True/False

        AnsweredTrue = new Command(async () =>
        {
            Debug.WriteLine("True button pressed");

            // check if answer is correct
            if (_currentAnswerValue == true)

                score++;
            else
            {
                Question _question = new Question();
                _question.Answer = true;
                _question.QuestionText = TextQuestion;
                errors.Add(_question);


            }


            // load next question or results page

            if (CurrentQuestionNumber < TotalQuestions)
            {
                // increase question counter
                CurrentQuestionNumber++;
                LoadQuestion();
            }
            else
            {
                Debug.WriteLine("End of Quiz");
                await ShowResults().ConfigureAwait(false);
            }
        });



        AnsweredFalse = new Command(async () =>
        {
            Debug.WriteLine("False button pressed");



            // check if answer is correct
            if (_currentAnswerValue == false) 
                score++;

            else
            {
                Question _question = new Question();
                _question.Answer = false;
                _question.QuestionText = TextQuestion;
                errors.Add(_question);

            }

            // load next question or results page
            if (CurrentQuestionNumber < TotalQuestions)
            {
                // increase question counter
                CurrentQuestionNumber++;
                LoadQuestion();
            }
            else
            {
                Debug.WriteLine("End of Quiz");
                await ShowResults().ConfigureAwait(false);
            }
        });
    }


    private void LoadQuestion()
    {
        var index = random.Next(questions.Count);
        TextQuestion= questions[index].QuestionText;
        CurrentAnswerValue = questions[index].Answer;
        questions.RemoveAt(index);
    }

    private async Task ShowResults() => await Application.Current.MainPage.Navigation.PushAsync(new TFResultsPage(errors, score, _totalQuestions));

}

}

On Shell Custom renderer have problem?

$
0
0

On Shell Custom renderer have problem? when I build the project my flyout menu and my bottom navigation tabbar background color are not working ?

custom renderer for bottom navigation tab font size smaller and bigger icon fontsize ? thanks

Project Class

public class CShell: AppShell
{

}

Adroid Class

[assembly: ExportRenderer(typeof(AppShell), typeof(CShellRenderer))]
namespace Goo4.Droid.Renderers
{
public class CShellRenderer : ShellRenderer
{
    public CShellRenderer(Context context) : base(context)
    {
    }
    protected override IShellBottomNavViewAppearanceTracker CreateBottomNavViewAppearanceTracker(ShellItem shellItem)
    {
        return new CBottomNavViewAppearanceTracker();
    }

}


public class CBottomNavViewAppearanceTracker : IShellBottomNavViewAppearanceTracker
{
   public void Dispose()
    {

    }

    public void ResetAppearance(BottomNavigationView bottomView)
    {

    }

    public void SetAppearance(BottomNavigationView bottomView, IShellAppearanceElement appearance)
    {
            IMenu menu = bottomView.Menu;
        for (int i = 0; i < bottomView.Menu.Size(); i++)
        {
            IMenuItem menuItem = menu.GetItem(i);
            var title = menuItem.TitleFormatted;
            SpannableStringBuilder sb = new SpannableStringBuilder(title);

            int a = sb.Length();

            //here I set fontsize 20
            sb.SetSpan(new AbsoluteSizeSpan(11, true), 0, a, SpanTypes.ExclusiveExclusive);

            menuItem.SetTitle(sb);
        }
    }
   }
}

ios Class

[assembly: ExportRenderer(typeof(AppShell), typeof(CShellRenderer))]
namespace Goo4.iOS.Renderers
{
    public class CShellRenderer : ShellRenderer
    {
        public CShellRenderer() : base()
        { }

        protected override IShellTabBarAppearanceTracker CreateTabBarAppearanceTracker()
        {
            return new CTabbarAppearance();
        }
    }

    public class CTabbarAppearance : IShellTabBarAppearanceTracker
    {
        public void Dispose()
        {

        }

        public void ResetAppearance(UITabBarController controller)
        {

        }

        public void SetAppearance(UITabBarController controller, ShellAppearance appearance)
        {

        }

        public void UpdateLayout(UITabBarController controller)
        {

        }
    }
}

Messaging app, background service

$
0
0

Hello people.

I'm developing an App similar to WhatsApp using Xamarin Forms (for Android and iOS), I use as Signal R Hub to communicate in real time.
The messages are recorded locally and on the server. I have already done all the logic of sending messages that could not be sent at the time due to lack of internet and downloading messages that were stopped on the server that were not received due to lack of internet.

So far so good. What I need now is to receive notification of new messages when the application is closed. When it is in the background, I usually notify the user because the hub is connected, but when the application is closed, it is not.

I don't know what the best approach is, if it is by push, if it would be something running in the background. If I can leave the hub running in the background or if it's better in the background to consume an API just to receive notifications ...

If anyone can help me I appreciate it.

Upload png or jpg to a server

$
0
0

Hello everyone. I hope you guys are doing OK

I have a problem: I need to update the profile picture of the user.

I am using @JamesMontemagno plugin, to take the picture or take the picture


Everything work fine an dandy

I need to update the actual file png or jpg to the API i am using (my server does not support bytes)

I tried a couple of things:

1)

var img = new Image {
                Source = Path.GetFileName(mediaFile.Path)
            };

Witch produce this error: Self referencing loop detected for property 'ParentView' with type 'Xamarin.Forms.Image'. Path 'avatar.Source'.'

2) I tried to use the File updater plugin, witch internally use a POST (https://github.com/CrossGeeks/FileUploaderPlugin/tree/master/src) and my api dont support post

3) I tried to sent get the filename, using

var image = Path.GetFileName(mediafile.path) \\ but image is of type string

this is my code to send to server:

public static async Task<HttpResponseMessage> UploadFileAsync(string token, Dictionary<string, Image> avatarImg) {

            var jsonString = JsonConvert.SerializeObject(avatarImg);
            var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");

            Debug.WriteLine("http" + httpContent.ToString());

            using (HttpClient client = new HttpClient()) {

                var serverAdress = Constants.AVATAR;
                client.DefaultRequestHeaders.Add("Authorization", "jwt " + token);

                var response = await client.PutAsync(serverAdress, httpContent);

                return response;
            }

the reason I am Jsonising my diccionary, is becouse my format is

{ avatar: picture_goes_here }
4) I tried sending bytes, but the server dosent undertand bytes (and the server is not mine)

I researched a little bit and they recommend using WebClient, but I want to use http client (is newer and faster)

That for the help in advance

Datepicker: Possible to bind to Nullable date value?

$
0
0

Hi everybody!

I have a nullable date field in my object and I want to bind a date picker to it. When the value is null, I would just want to show no value in the picker. Is this possible?

I tried

datepicker.SetBinding (DatePicker.DateProperty, vm => vm.DueDate, BindingMode.TwoWay);

but this results in a NullValueException when the view is shown.

Any ideas?

Override built-in ColorTypeConverter with custom TypeConverter?

$
0
0

Hi! We have a solution where we have an project containing various constants (which are used throughout a few separate application), such as colors. As this project does not use Xamarin in any way shape or form, it cannot use the Xamarin.Forms.Color class but instead describes these colors with our custom SharedConstants.Color class.

We want to be able to reference these colors directly throughout the app, both in C# and XAML. For the former case, it seems perfectly reasonable (if a little verbose) to have an extension method Xamarin.Forms.Color ToXamarin(this SharedConstants.Color color) to solve this. However, for using our SharedConstants.Color in XAML we are drawing a bit of a blank. The naive solution would be to create a wrapper around the constants, with a static class with properties mapping between the constants as follows (which could then be referenced in XAML with x:Static):

public static class FormsColors {
    public static Xamarin.Forms.Color HighlightColor => SharedConstants.Colors.HighlightColor.ToXamarin();
    ...
}

This is not an entirely satisfactory solution due to essentially duplicating code and requiring adding a new color in two separate files each time a new color should be added.

From digging around the Xamarin.Forms source, I see that a class ColorTypeConverter is used for transforming strings in XAML to instances of Xamarin.Forms.Color. Would it be possible to create a subclass to ColorTypeConverter and export that as the go-to TypeConverter for converting values to Xamarin.Forms.Color? It seems like ColorTypeConverter is registered as the TypeConverter for Color at a few different locations:

  • In BindableProperty.cs, line 40
  • In Color.cs, line 10
  • In ColorTypeConverter.cs, line 9

Is there a way of overriding these somehow with a custom ColorTypeConverter?


Call a fuction from viewModel to code behind for VisualStateManager.GoToState

$
0
0

I started using prism & I have a data snapshot listener in my viewModel which automatically calls a function in my viewModel whenever data is updated

I wanted to update visualState in my page based on the updated data, So how do I call a code behind method from the viewModel,

Or more like:
Whenever A value in my viewmodel is updated, how do I call a function in the code behind

AlarmManager calendar/exact half hour

$
0
0

I want to use the AlarmManager to schedule a task each half an hour. I managed to do this by doing:

alarmManager.SetInexactRepeating(AlarmType.RtcWakeup, 0, 1000 * 60 * 30, pendingIntent);

However, if this is called at lets say at 18:09:00, then next task will be called at 18:39:00, 19:09:00, 19:39:00, 20:09:00 etc...

I would like to schedule it so it (inexactly) calls at 18:00:00, 18:30:00, 19:00:00, 19:30:00, 20:00:00 etc, i.e. full half-hour/exact half hour.

I guess I could use the triggerAtMillis (parameter 2) to tweak it but I do not understand how? Any guidance of how to do that?

As a side question on this topic, is the AlarmManager draining a lot of battery to schedule?

System.IO.FileNotFoundException: Could not find file “/data/user/0/com.abshar.app/files/xxxx.json

$
0
0

I'm trying to use google translate api. So I downloaded the service account json file from google cloud. And I put the json file in Files folder in my Android project. I have used numerous codes but I'm not able to access the json file. I'm getting this exception

System.IO.FileNotFoundException: Could not find file "/data/user/0/com.abshar.app/files/xxx-280817-bedb566bfd11.json" at System.IO.FileStream

This is my code in xaml.cs

string jsonpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal),"xxxx-280817-bedb566bfd11.json");
                System.IO.File.OpenRead(jsonpath);
                System.IO.File.ReadAllText(jsonpath);
                System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS",jsonpath);

                TranslationClient client = TranslationClient.Create();

I dont have any clue how to fix this. Any suggestions?

PropertyChanged is not null although we don't subscribe any function to it. How come?

$
0
0

I implement INotifyPropertyChanged and it works fine.

There is something I don't understand though: PropertyChanged is a an event, which means it is a delegate.

Before we invoke event/delegate we need them to point on some function/eventHundler ("Subscribe") -
otherwise the event will be null.

How is it, that here we declare an event, I didn't subscribe no one to this event, and still - it is not null.

public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
   var changed = PropertyChanged;
    if (changed == null)   //It seems for me, this should be null for ever.  
       return;
    changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
}~~~~

how to manage a searchbar that get data from existing listview xamarin

$
0
0

i'have searched for this so many times all i can find is people using the list view and insert the data , for my case the listview's data is from an excel file

My app is opening inside the whatsapp when I click my app link in whatsapp

$
0
0

Hi, I have implemented the sharing feature with Whatsapp. Here we can share the forums through whatsapp. When I share a forum, I will include image and text along with my app url and send to end user.

Currently My app is running inside the whatsapp when the end user clicks on my shared link.
How can I open my app as a separate app instead of running in whatsapp?

Here is my code using in MainActivity.

[IntentFilter(new[] { Intent.ActionView },
Categories = new[]
{
Intent.ActionView,
Intent.CategoryDefault,
Intent.CategoryBrowsable
},
DataScheme = "https",
DataHost = "sampleapp.co.in",
DataPathPrefix = "/",
AutoVerify = true)
]

[IntentFilter(new[] { Intent.ActionView },
    Categories = new[]
    {
        Intent.ActionView,
        Intent.CategoryDefault,
        Intent.CategoryBrowsable
    },
    DataScheme = "http",
    DataHost = "sampleapp.co.in",
    DataPathPrefix = "/",
    AutoVerify = true)
      ]      

Thanks in advance.

WindowSoftInputMode="Resize" SHELL issues

$
0
0
Hello,
I have a login screen with two entry fields for email and password with a login button.
I am using WindowSoftInputmode in android to make sure the entries are visible when the soft keyboard is displayed.
I am using The Xarin Forms Shell with bottom Navigation(tabbar). When the keyboard is displayed the bottom bar is being pushed up and displayed above the keyboard.
Any idea how I can tackle this issue and make sure my bottom navigation is not displayed above the keyboard?

How to change App Shell selected tab text size on Android?

$
0
0

On iOS it's fine but on Android a tab's font size increases if the tab is selected which in my application causes the text to be truncated. I've tried setting 'actionBarTabTextStyle' and 'actionBarStyle' in my theme in the Android project and creating a custom renderer for TabbedPage as per this page but neither of those solutions appear to work. Any would be greatly appreciated :)

Can't get points to be implemented with bindable Objects

$
0
0

Hello there. I have a line of which I want to be able to change it's points based on a point list i have made. This is how my xaml looks:
<Path StrokeThickness="3" Stroke="PaleGoldenrod" StrokeLineCap="Round"> <Path.Data> <PathGeometry> <PathGeometry.Figures> <PathFigureCollection> <PathFigure StartPoint="{Binding pointz}"> <PathFigure.Segments> <PathSegmentCollection> <BezierSegment Point1="{Binding pointo}" Point2="{Binding pointt}" Point3="{Binding pointth}" /> </PathSegmentCollection> </PathFigure.Segments> </PathFigure> </PathFigureCollection> </PathGeometry.Figures> </PathGeometry> </Path.Data> </Path>

but even though it can read the binding pointo etc and can show them as a label it doesn't take them as a Point. My points derive from this class:
public Point pointz { get; set; } public Point pointo { get; set; } public Point pointt { get; set; } public Point pointth { get; set; }
Why is this happening? Am I missing something? Simply writing the points works but binding them seems to have no effect...
Thanks in advance.

Xamarin - Microsoft App Center Release mode

$
0
0

Hi,

I have enabled the App Center diagnostics for my app since my background service keep crashing my app when the AlarmManager tries to wake it up and I have no idea of how to get to the bottom of it what is actually going wrong. I have enabled App Center like this here: https://docs.microsoft.com/en-us/appcenter/sdk/getting-started/xamarin

Is there no way to make App Center also to report crashes when compiled in Release mode (Android)? I would like to keep this diagnostics for a long period of time in our production environment.

How to add BoxView in relative layout with WidthConstraint dependent on external data

$
0
0

Hi guys,

I'm currently trying to display tasks with BoxViews like this

However the width of this BoxViews should be dependent on the length of the task at hand.
I tried this with RelativeLayout + BoxViews and tried DataBinding on the Constraint Factor but then found out DataBinding is not useable in ConstraintExpressions.
Does anyone has a straight forward solution to this issue that doesn't come to my mind?

Also if you have an idea how I can archieve the same outcome with another method, please let me know

Sorry if its something obvious I'm not aware of yet, I'm a newbie in Xamarin Forms.
Thanks in advance!

How to fix cinema hd not streams?

$
0
0

Hi everybody,
My cinema hd app suddenly didn't work, it announced non-streaming programs and movies. I have checked the connection as well as restarting the device but the situation has not improved.
Right now I am unable to do anything with free cinema, whether it is having difficulties. Someone had a problem please help me solve it.
Thanks for reading.

Viewing all 79144 articles
Browse latest View live


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