I want to display a list of photos in a Pivot Control, so I have this xaml
<Grid x:Name="LayoutRoot" Background="Transparent">
<controls:Pivot x:Name="DiaporamaPivot">
</controls:Pivot>
</Grid>
and in the code behind I do :
public Diaporama()
{
InitializeComponent();
PivotItem p = new PivotItem();
Image i = new Image();
i.Source = new BitmapImage(new Uri("/image.jpg", UriKind.Relative));
p.Margin = new Thickness(0, -10, 0, -2);
DiaporamaPivot.Items.Add(i);
}
Any idea why I get an exception
You are adding i (Image) to Pivot. Instead, add i to p and then, add p (PivotItem) to Pivot.
public Diaporama()
{
InitializeComponent();
PivotItem p = new PivotItem();
Image i = new Image();
i.Source = new BitmapImage(new Uri("/image.jpg", UriKind.Relative));
p.Margin = new Thickness(0, -10, 0, -2);
p.Content = i;
DiaporamaPivot.Items.Add(p);
}
Related
I'm trying to create an NavigationPage TitleView with traditional Cart Icon saying (3) Items etc.
So the global CartCount variable is Declared in App class.
My CommonToolbarPage class Lays out the top of all 50 pages with Logo, search button and Cart icon like every shop on the internet. I'm using Prism.
What I'm after is what goes here to bind to CartCount so BadgeText updates when the CartCount updates.
BadgeText = App.CartCount , // Jiberish
Cut down class
public class CommonToolbarPage : ContentPage
{
public CommonToolbarPage()
{
//NavigationPage.SetHasBackButton(this, false);
ShowDefaultTitle();
//this.BindingContext= new CommonToolbarPageViewModel(navigationService);
}
private void ShowDefaultTitle()
{
SfButton sfButton = new SfButton
{
CornerRadius = 4,
HorizontalOptions = LayoutOptions.End,
VerticalOptions = LayoutOptions.Center,
Style = (Style)Application.Current.Resources["IconButtonStyle"],
Text = (String)Application.Current.Resources["Cart"],
FontFamily = "UIFontIcons",
TextColor = Color.White,
// Command = new Command(GoCart)
};
var Endlayout = new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.EndAndExpand,
};
var imSfBadgeView = new SfBadgeView
{
BadgeText = App.Cart, // Jiberish
Margin = new Thickness(0, 0, 10, 0),
Padding = new Thickness(0),
WidthRequest = 40,
// Content = sfButton,
HorizontalOptions = LayoutOptions.EndAndExpand,
VerticalOptions = LayoutOptions.Center,
BackgroundColor = Color.Transparent,
BadgeSettings = new BadgeSetting
{
BackgroundColor = (Color)Application.Current.Resources["PrimaryColor"],
BadgeType = BadgeType.None,
FontSize = 10,
Stroke = (Color)Application.Current.Resources["Gray-White"],
StrokeWidth = 1,
Offset = new Point(-10, 10)
}
};
Endlayout.Children.Add(imSfBadgeView);
NavigationPage.SetTitleView(this, Endlayout);
}
}
Each page then looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<local1:CommonToolbarPage xmlns:local1="clr-namespace:blaAppV1.Views.Templates"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:listview="clr-namespace:Syncfusion.ListView.XForms;assembly=Syncfusion.SfListView.XForms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:prism="http://prismlibrary.com"
prism:ViewModelLocator.AutowireViewModel="True"
xmlns:local="clr-namespace:blaAppV1.Views;assembly=blaAppV1"
x:Class="blaAppV1.Views.Home">
<StackLayout VerticalOptions="StartAndExpand" HorizontalOptions="Center">
<Label Text="Home" VerticalOptions="Center" HorizontalOptions="Center" />
<Button Text="Appliances" Command="{Binding Path=NavigateCommand}" CommandParameter="Appliances" />
</StackLayout>
</local1:CommonToolbarPage>
you use SetBinding to create a binding in code
myLabel.SetBinding(Label.TextProperty, "CartCount");
myLabel.BindingContext = App;
I'm developing a Xamarin Forms iOS app. In the xaml file, there is a grid.
<Grid x:Name="QrCodeSite" HeightRequest="300" Margin="37, 37, 37, 0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
</Grid>
In the related .cs file, I use ZXing.Net.Mobile.Forms to generate a QR code and place it in the grid. And I put my logo in the same grid, which will finally appear at the center of the QR code.
var barcode = new ZXingBarcodeImageView
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand
};
barcode.BarcodeFormat = ZXing.BarcodeFormat.QR_CODE;
barcode.BarcodeOptions.Width = 650;
barcode.BarcodeOptions.Height = 650;
barcode.BarcodeOptions.Margin = 1;
barcode.BarcodeValue = value;
var img = new Image
{
Source = "logo.png",
WidthRequest = 70,
HeightRequest = 70,
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center
};
QrCodeSite.Children.Clear();
QrCodeSite.Children.Add(barcode);
QrCodeSite.Children.Add(img);
The problem is, maybe my phone (iPhone 6s plus) is too slow, sometimes the logo appears first and after a lag (around 1 second) the QR code is shown. How can I merge the QR code and the logo into one image and then add it to the grid?
You can using SkiaSharp to display Image or merge images . Having a look at how to Display SkiaSharp bitmaps to download sample project to research at it.
Based on Drawing on existing bitmaps reference , you can modify it as follow :
public partial class MonkeyMoustachePage : ContentPage
{
SKBitmap monkeyBitmap;
public MonkeyMoustachePage()
{
Title = "Monkey Moustache";
monkeyBitmap = BitmapExtensions.LoadBitmapResource(GetType(),
"SkiaSharpFormsDemos.Media.MonkeyFace.png");
SKBitmap iconImage = BitmapExtensions.LoadBitmapResource(GetType(),
"SkiaSharpFormsDemos.Media.GooglePlaylogo.png");
int offset = monkeyBitmap.Width / 2 - iconImage.Width / 2;
int offsetTop = monkeyBitmap.Height / 2 - iconImage.Height / 2;
// Create canvas based on bitmap
using (SKCanvas canvas = new SKCanvas(monkeyBitmap))
{
canvas.DrawBitmap(iconImage, SKRect.Create(offset, offsetTop, iconImage.Width, iconImage.Height));
}
// Create SKCanvasView to view result
SKCanvasView canvasView = new SKCanvasView();
canvasView.PaintSurface += OnCanvasViewPaintSurface;
Content = canvasView;
//save the new image
using (MemoryStream memStream = new MemoryStream())
using (SKManagedWStream wstream = new SKManagedWStream(memStream))
{
monkeyBitmap.Encode(wstream, imageFormat, quality);
byte[] data = memStream.ToArray();
// Check the data array for content!
bool success = await DependencyService.Get<IPhotoLibrary>().SavePhotoAsync(data, folder, filename);
// Check return value for success!
}
}
void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
{
SKImageInfo info = args.Info;
SKSurface surface = args.Surface;
SKCanvas canvas = surface.Canvas;
canvas.Clear();
canvas.DrawBitmap(monkeyBitmap, info.Rect, BitmapStretch.Uniform);
}
}
Then you will see a logo icon will display in original image :
If you want to save SkiaSharp bitmaps to files , have a look at this :https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/bitmaps/saving#exploring-the-image-formats
Note: BitmapExtensions.cs file is from sample project .By the way , when adding image to project , you need to set Build ACtion of image be Embedded resource .As follow :
I want to display text in a format in label, but it's displaying an incorrect value.
It's showing the correct value in debug mode. But its displayed wrong on the screen. Ideally, the screen should display total and subtotal as image one.
Code to format string
string paymentFormat = "{0,-25} {1,8}\n";
string paymentMode = "Total"; // Or Subtotal
string paymentAmount = "604.00";
string test = string.Format(paymentFormat, paymentMode, paymentAmount);
Update
public class AlertPopupViewItem : ContentView
{
Label HeaderLabel,MessageLabel;
public Button OKButton, CancelButton;
AbsoluteLayout _overlay;
LoggerService logservice;
public bool ButtonValue = false;
StackLayout CancelStackLayout, OKStackLayout;
string PageSource = string.Empty;
public AlertPopupViewItem()
{
logservice = new LoggerService();
logservice.WriteData(Constants.DEBUG_LOGGING, "Alert Message Popup ctor.. Start");
_overlay = new AbsoluteLayout
{
BackgroundColor = Color.Black.MultiplyAlpha(0.5),
HorizontalOptions = LayoutOptions.Fill,
VerticalOptions = LayoutOptions.Fill,
};
Grid mainGrid = new Grid
{
HeightRequest = 40,
BackgroundColor = Color.White,
Padding = 20,
RowDefinitions =
{
new RowDefinition { Height = new GridLength(15, GridUnitType.Star) },//0 Title
new RowDefinition { Height = new GridLength(3, GridUnitType.Star) },//1 Line
new RowDefinition { Height = new GridLength(80, GridUnitType.Star) },//2 Message
new RowDefinition { Height = new GridLength(12, GridUnitType.Star) },//3 OK-Cancel
}
};
HeaderLabel = new Label
{
FontAttributes = FontAttributes.Bold,
FontSize = 22,
TextColor = Color.Black,
HorizontalTextAlignment= TextAlignment.Center,
VerticalTextAlignment = TextAlignment.Center,
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions =LayoutOptions.CenterAndExpand
};
BoxView divider = new BoxView
{
HeightRequest = 1,
Color = Color.Gray,
VerticalOptions = LayoutOptions.End,
};
MessageLabel = new Label
{
FontAttributes = FontAttributes.None,
FontSize = 13,
HorizontalTextAlignment = TextAlignment.Start,
VerticalTextAlignment = TextAlignment.Center,
HorizontalOptions = LayoutOptions.StartAndExpand,
TextColor = Color.Black
};
ScrollView scroll = new ScrollView()
{
Orientation = ScrollOrientation.Vertical
};
scroll.Content = MessageLabel;
Grid ButtonGrid = new Grid
{
HeightRequest = 35,
ColumnDefinitions =
{
new ColumnDefinition {Width=new GridLength(58,GridUnitType.Star) },
new ColumnDefinition {Width=new GridLength(20,GridUnitType.Star) },
new ColumnDefinition {Width=new GridLength(2,GridUnitType.Star) },
new ColumnDefinition {Width=new GridLength(20,GridUnitType.Star) }
}
};
CancelStackLayout = new StackLayout
{
Padding = new Thickness(-6, -6, -6, -6),
//VerticalOptions = LayoutOptions.Center,
BackgroundColor = Color.FromHex("#ff9500")
};
CancelButton = new Button
{
TextColor = Color.White,
FontSize = 15,
BorderRadius = 0,
Text = Localizer.Localize("CancelSmall"),
BackgroundColor = Color.FromHex("#01458e"),
HorizontalOptions =LayoutOptions.FillAndExpand,
VerticalOptions=LayoutOptions.FillAndExpand,
BorderColor = Color.Transparent
};
CancelButton.Clicked += CancelButtonClicked;
CancelStackLayout.Children.Add(CancelButton);
ButtonGrid.Children.Add(CancelStackLayout, 1, 0);
OKStackLayout = new StackLayout
{
Padding = new Thickness(-6, -6, -6, -6),
BackgroundColor = Color.FromHex("#ff9500")
};
OKButton = new Button
{
TextColor = Color.White,
FontSize = 15,
BorderRadius = 0,
Text = Localizer.Localize("OK"),
BackgroundColor = Color.FromHex("#01458e"),
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
BorderColor = Color.Transparent
};
OKButton.Clicked += OKButtonClicked;
OKStackLayout.Children.Add(OKButton);
ButtonGrid.Children.Add(OKStackLayout, 3, 0);
mainGrid.Children.Add(HeaderLabel, 0, 0);
mainGrid.Children.Add(divider, 0, 1);
mainGrid.Children.Add(scroll, 0, 2);
mainGrid.Children.Add(ButtonGrid, 0, 3);
AbsoluteLayout.SetLayoutFlags(mainGrid, AbsoluteLayoutFlags.All);
AbsoluteLayout.SetLayoutBounds(mainGrid, Findlayoutbounds(new Rectangle(0.20, 0.25, 0.5, 0.50)));
_overlay.Children.Add(mainGrid);
Content = _overlay;
logservice.WriteData(Constants.DEBUG_LOGGING, "Alert Message Popup ctor.. End");
}
// ThreadHandle thread = new ThreadHandle();
private void CancelButtonClicked(object sender, EventArgs e)
{
ButtonValue = false;
this.IsVisible = false;
// thread.WorkMethod();
}
private void OKButtonClicked(object sender, EventArgs e)
{
ButtonValue = true;
if (PageSource == "StarterPage") ;
//MessagingCenter.Send(this, "ModifyValBooleanForAlert");
this.IsVisible = false;
// thread.WorkMethod();
}
Rectangle Findlayoutbounds(Rectangle fractionalRect)
{
if (fractionalRect.Width - 1 == 0)
fractionalRect.Width = 0.99;
if (fractionalRect.Height - 1 == 0)
fractionalRect.Height = 0.99;
Rectangle layoutbounds = new Rectangle
{
X = fractionalRect.X / (1 - fractionalRect.Width),
Y = fractionalRect.Y / (1 - fractionalRect.Height),
Width = fractionalRect.Width,
Height = fractionalRect.Height
};
return layoutbounds;
}
public void DisplayAlertPopup(string alertBoxTitle, string alertBoxContent,bool CancelDisplay)
{
HeaderLabel.IsVisible = false;
CancelStackLayout.IsVisible = CancelDisplay;
CancelButton.IsVisible = CancelDisplay;
HeaderLabel.Text = alertBoxTitle;
MessageLabel.Text = alertBoxContent;
OKButton.Text = Localizer.Localize("OK");
CancelButton.Text = Localizer.Localize("CancelSmall");
HeaderLabel.IsVisible = true;
}
public void DisplayAlertPopup(string alertBoxTitle, string alertBoxContent, string ButtonText)
{
CancelStackLayout.IsVisible = false;
CancelButton.IsVisible = false;
HeaderLabel.Text = alertBoxTitle;
MessageLabel.Text = alertBoxContent;
OKButton.Text = ButtonText;
}
public void DisplayAlertConditionalPopup(string alertBoxTitle, string alertBoxContent, bool CancelDisplay)
{
CancelStackLayout.IsVisible = CancelDisplay;
CancelButton.IsVisible = CancelDisplay;
HeaderLabel.Text = alertBoxTitle;
MessageLabel.Text = alertBoxContent;
this.IsVisible = true;
}
public void SetButtonText(string OKText, string CancelText)
{
if (OKText != null)
OKButton.Text = OKText;
if (CancelText != null)
CancelButton.Text = CancelText;
}
}
I get the formatted string from some other class and call the DisplayAlertPopup method. MessageLabel is the label for which I am setting this value.
Update2:
As suggested in answer, I have tried the below code to set the font for Android. But its also not displying the text in the required format.
MessageLabel = new Label
{
FontAttributes = FontAttributes.None,
FontSize = 13,
HorizontalTextAlignment = TextAlignment.Start,
VerticalTextAlignment = TextAlignment.Center,
HorizontalOptions = LayoutOptions.StartAndExpand,
TextColor = Color.Black,
FontFamily = "Droid Sans Mono"
};
You will need to use a fixed-width font. There is unfortunately none that is built-in across all platforms, but each platform has its own:
iOS - Courier New
Android - Droid Sans Mono
UWP - Consolas
If no built-in font suits you or you want to have the same experience on all platforms, you can also use custom fonts in Xamarin.Forms. This requires you to find a fixed-width font you like on a service like Google Fonts. Then you can follow the tutorial here on Xamarin Help, that describes how to include the TTF file in each platform and use it from XAML.
The short summary is:
Add the font to each platform project with appropriate build action (UWP - Content, iOS - Bundle Resource, Android - Android Asset)
Use the OnPlatform syntax to set the font (ideally creating a static resource so that it can be reused):
Resource:
<OnPlatform x:TypeArguments="x:String" x:Key="MyFontFamily">
<On Platform="Android" Value="MyFont.ttf#Open Sans" />
<On Platform="UWP" Value="/Assets/MyFont.ttf#Open Sans" />
<On Platform="iOS" Value="MyFont" />
</OnPlatform>
And use like this:
<Label FontFamily="{StaticResource MyFontFamily}" />
I have a StackLayout holding some elements for a custom cell in a ListView. The problem I am running in to is that my images are not landing on full pixel boundaries. This is causing the straight lines in my graphics to become blurry as they are not landing on pixel boundaries. Is there a way for me to easily prevent this behavior, perhaps in a custom renderer?
public InputEditCell()
{
image = new Image { HorizontalOptions = LayoutOptions.Start };
image.SetBinding(Image.SourceProperty, new Binding("Image.ImageNameSelect"));
image.BindingContext = _tempInputViewModel;
var tappedImageGesture = new TapGestureRecognizer
{
Command = new Command(OnImageTapped),
CommandParameter = image
};
image.GestureRecognizers.Add(tappedImageGesture);
nameEntry = new Entry()
{
TextColor = Color.FromHex("E60006"),
FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Entry)),
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.FillAndExpand
};
nameEntry.SetBinding(Entry.TextProperty, "Name");
nameEntry.BindingContext = _tempInputViewModel;
var acceptImage = new Image
{
Source = ResourceHandler.GetAcceptImage(),
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.End,
};
var tappedAcceptGesture = new TapGestureRecognizer
{
Command = new Command(OnAcceptTapped),
CommandParameter = acceptImage
};
acceptImage.GestureRecognizers.Add(tappedAcceptGesture);
var cancelImage = new Image
{
Source = ResourceHandler.GetCancelImage(),
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.End,
};
var tappedCancelGesture = new TapGestureRecognizer
{
Command = new Command(OnCancelTapped),
CommandParameter = cancelImage
};
cancelImage.GestureRecognizers.Add(tappedCancelGesture);
var viewLayout = new StackLayout {
Orientation = StackOrientation.Horizontal,
Children = { image, nameEntry, acceptImage, cancelImage },
Padding = new Thickness(10, 10, 10 ,10)
};
View = viewLayout;
View.GestureRecognizers.Clear();
View.GestureRecognizers.Add(new TapGestureRecognizer());
}
Is there a way to create a custom ShellTile that displays at start (after user pins our app)? I would like to resize and reposition a count number (label), but I can't find a way to do that.
You can't change the position or style of title or counter, but you can generate an image to display on the tile, for example:
WriteableBitmap bitmap = new WriteableBitmap(173, 173);
TextBlock textBlock = new TextBlock();
textBlock.TextWrapping = TextWrapping.Wrap;
textBlock.Foreground = new SolidColorBrush(Colors.White);
textBlock.FontSize = 22.0;
textBlock.Margin = new Thickness(12.0, 8.0, 8.0, 45.0);
textBlock.Text = "Lorem ipsum";
textBlock.HorizontalAlignment = HorizontalAlignment.Stretch;
textBlock.VerticalAlignment = VerticalAlignment.Stretch;
Grid layoutRoot = new Grid();
layoutRoot.Background = (Brush)App.Current.Resources["PhoneAccentBrush"];
layoutRoot.Width = 173.0;
layoutRoot.Height = 173.0;
layoutRoot.Children.Add(textBlock);
layoutRoot.Measure(new Size(173, 173));
layoutRoot.Arrange(new Rect(0, 0, 173, 173));
layoutRoot.UpdateLayout();
bitmap.Render(layoutRoot, null);
bitmap.Invalidate();
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
string fileName = "/Shared/ShellContent/BackgroundImage.jpg";
using (Stream fileStream = storage.CreateFile(fileName))
{
bitmap.SaveJpeg(fileStream, 173, 173, 0, 100);
}
}
StandardTileData tileData = new StandardTileData
{
BackgroundImage = new Uri("isostore:"/Shared/ShellContent/BackgroundImage.jpg, UriKind.Absolute),
Title = "Lorem Ipsum,
};
ShellTile.Create(new Uri("/MainPage.xaml", UriKind.Relative), tileData);