ChartView within StackLayout cuts off Chart - c#

Here is my code:
List<Entry> entries = new List<Entry>
{
new Entry(7)
{
Color = SKColor.Parse("#166DA3"),
},
new Entry(3)
{
Color = SKColors.Transparent,
}
};
public RoundScore2()
{
Content = _contentLayout; // layout inherited from a different class
Label congrats = new Label
{
Text = "Congratulations!",
FontAttributes = FontAttributes.Bold,
FontSize = 30,
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.Start,
TextColor = Color.Black
};
_contentStack.Children.Add(congrats); // _contentStack inherited from same class, _contentStack is added to _contentLayout
ChartView Chart1 = new ChartView
{
VerticalOptions = LayoutOptions.CenterAndExpand,
HeightRequest = 80
};
_contentStack.Children.Add(Chart1);
Chart1.Chart = new DonutChart() { Entries = entries, HoleRadius = 5 };
Button nextRound = new Button
{
Text = "Start Round " + roundCounter.ToString(),
Margin = new Thickness(10, 20, 10, 10),
TextColor = Color.Black,
BackgroundColor = Color.FromHex("48AADF"),
FontFamily = "Source Sans Pro",
FontSize = 20,
FontAttributes = FontAttributes.Bold,
CornerRadius = 8,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.StartAndExpand,
WidthRequest = 180
};
_contentStack.Children.Add(nextRound);
}
Stack overflow is not letting me add the photo right now ("Failed to upload image; couldn't reach imgur")...but basically, I can only see the horizontal middle section of the pie chart. There is enough space for the chart to show, but it is just cut off. I have tried setting VerticalOptions = LayoutOptions.FillAndExpand along with LayoutOptions.CenterAndExpand and no luck. Does anyone know why this is happening?
Edit: even with the Label and Button taken out, the view is still cut off.

but basically, I can only see the horizontal middle section of the pie chart.
From shared code of ChartView, I'm guessing that whether the width of chart view is too small.
ChartView Chart1 = new ChartView
{
VerticalOptions = LayoutOptions.CenterAndExpand,
HeightRequest = 80
};
If so , you can add HorizontalOptions as follow:
ChartView Chart1 = new ChartView
{
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
HeightRequest = 80
};
In addition , also can add HorizontalOptions for StackLayout:
_contentStack.HorizontalOptions = LayoutOptions.FillAndExpand;
_contentStack.VerticalOptions = LayoutOptions.FillAndExpand;

It worked after changing VerticalOptions = LayoutOptions.Center and HorizontalOptions = LayoutOptions.Fill as well as changing HoleRadius = .5f.

Related

Xamarin maximum grid row/ column definitions

I've only started playing with xamarin recently but I'm making a roguelike using xamarin and I had the idea of using a grid for the player map (each X Y position in the grid would be representing the randomly generated map) I've hit a snag though in that putting things any thing over the 55th column seems to push them off the screen (See image below)
Here's my code so far:
StackLayout stackLayout = new StackLayout() { VerticalOptions = LayoutOptions.FillAndExpand };
Grid grid = new Grid
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
};
stackLayout.Children.Add(grid);
for (int i = 0; i < 300; i++)
{
grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
}
// Row 0
// The BoxView and Label are in row 0 and column 0, and so only needs to be added to the
// Grid.Children collection to get default row and column settings.
grid.Children.Add(new BoxView
{
Color = Color.Green
});
grid.Children.Add(new Label
{
Text = "Row 0, Column 0",
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center
});
// This BoxView and Label are in row 0 and column 1, which are specified as arguments
// to the Add method.
grid.Children.Add(new BoxView
{
Color = Color.Blue
}, 55, 0);
grid.Children.Add(new Label
{
Text = "Row 0, Column 1",
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center
}, 1, 0);
// Row 1
// This BoxView and Label are in row 1 and column 0, which are specified as arguments
// to the Add method overload.
grid.Children.Add(new BoxView
{
Color = Color.Teal
}, 0, 1, 1, 2);
grid.Children.Add(new Label
{
Text = "Row 1, Column 0",
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center
}, 0, 1, 1, 2); // These arguments indicate that that the child element goes in the column starting at 0 but ending before 1.
// They also indicate that the child element goes in the row starting at 1 but ending before 2.
grid.Children.Add(new BoxView
{
Color = Color.Purple
}, 1, 2, 1, 2);
grid.Children.Add(new Label
{
Text = "Row1, Column 1",
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center
}, 1, 2, 1, 2);
// Row 2
// Alternatively, the BoxView and Label can be positioned in cells with the Grid.SetRow
// and Grid.SetColumn methods.
BoxView boxView = new BoxView { Color = Color.Red };
Grid.SetRow(boxView, 2);
Grid.SetColumnSpan(boxView, 2);
Label label = new Label
{
Text = "Row 2, Column 0 and 1",
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center
};
Grid.SetRow(label, 2);
Grid.SetColumnSpan(label, 2);
grid.Children.Add(boxView);
grid.Children.Add(label);
Title = "Basic Grid demo";
Content = grid;
So I guess the question is a few folds, how can I "Zoom" out on the grid view to see the other cells of the grid? Additionally, am I even going about this the right way ? or is there a better approach that using a grid?
You should warp the content into a ScrollView and set Content = scrollView, then you can scroll to see all the elements:
public MainPage()
{
InitializeComponent();
StackLayout stackLayout = new StackLayout() { VerticalOptions = LayoutOptions.FillAndExpand };
Grid grid = new Grid
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
};
stackLayout.Children.Add(grid);
//......
grid.Children.Add(boxView);
grid.Children.Add(label);
Title = "Basic Grid demo";
//warp the content into a ScrollView
ScrollView scrollView = new ScrollView { Content = stackLayout };
scrollView.Orientation = ScrollOrientation.Both;
Content = scrollView;
}

Xamarin - Image overflowing StackLayout

I am trying to make a gallery style grid view in Xamarin forms for iOS and Android but have an issue where layout options seem to be ignored and I get different results for iOS and Android.
Basic layout is:
frame with a border(red) containing a stack layout (pink) set to FillAndExpand for both horizontal and vertical options which contains a label at the top and an image below set to fill the rest of the stack.
The image seems to just expand outside of the stack and the frame and ignore the vertical options set.
I have tried setting these vertical options to Fill, FillAndExpand, CentreAndExpand but all have the same result.
If i remove the Stack layout and label and have the image as the only child element in the frame then it works as expected but I am required to also show a label.
The result is the same in landscape and portrait orientations.
Results on platform with iOS being the main issue here:
Code for adding an image to the grid:
var imageSource = ImageSource.FromStream(() => new MemoryStream(imageData));
var framedImage = new Frame
{
Padding = 0,
Margin = 3,
GestureRecognizers = { tapGesture },
Content = new StackLayout
{
Padding = 10,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
BackgroundColor = Color.Pink,
Children =
{
textLabel,
new Image
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand,
Source = imageSource,
Aspect = Aspect.AspectFit
},
}
},
BackgroundColor = StyleSheet.BackgroundColorLight,
BorderColor = StyleSheet.OutlineColorDark,
CornerRadius = 5,
HasShadow = false
};
grid.Children.Add(framedImage, columnCounter, rowCounter);
Thanks in advance!
Fixed it by doing this:
var image = new Image
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
Source = imageSource,
Aspect = Aspect.AspectFit
};
var framedImage = new Frame
{
Padding = 2,
Margin = 1,
GestureRecognizers = { tapGesture },
Content = image,
HasShadow = false,
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand
};
var innergrid = new Grid
{
RowDefinitions =
{
new RowDefinition {Height = new GridLength(20, GridUnitType.Auto)},
new RowDefinition {Height = new GridLength(20, GridUnitType.Star)},
}
};
innergrid.Children.Add(textLabel, 0, 0);
innergrid.Children.Add(framedImage, 0, 1);
var frame = new Frame
{
Padding = 5,
Margin = 3,
GestureRecognizers = { tapGesture },
Content = innergrid,
BackgroundColor = StyleSheet.BackgroundColorLight,
BorderColor = StyleSheet.OutlineColorDark,
CornerRadius = 5,
HasShadow = true
};
grid.Children.Add(frame, columnCounter, rowCounter);
I might have a go with the new FlexLayout to see if i can have simpler code

Using Xamarin ZXing.Net.Mobile - scanner stretched = ISSUE

I am currently using the package ZXing.Net.Mobile for Xamarin Forms.
I want content on the top of the screen and at the bottom of the screen and I want the scanner to be somewhere in the middle.
If I specify the height of the scanner, it stretches it making it ugly and not nice to have (because the scanner is meant to be used for full screen?).
I want to have some content on the top of the screen with a dynamic height, then I want the scanner with height 150-200, then I want some content to be shown on the rest of the screen.
I was looking into ZXingDefaultOverlay but I could not get it to work as I wanted.
Anyone has an idea, example or an answer that can help me?
Following is the sample code where I have used Grid
for showing content on top and bottom of the screen and middle screen contains scanner.
public ZXingDefaultOverlay()
{
BindingContext = this;
RowSpacing = 0;
VerticalOptions = LayoutOptions.FillAndExpand;
HorizontalOptions = LayoutOptions.FillAndExpand;
RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
RowDefinitions.Add(new RowDefinition { Height = new GridLength(2, GridUnitType.Star) });
RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
Children.Add(new BoxView
{
VerticalOptions = LayoutOptions.Fill,
HorizontalOptions = LayoutOptions.FillAndExpand,
BackgroundColor = Color.Transparent,
Opacity = 0.7,
}, 0, 0);
Children.Add(new BoxView
{
VerticalOptions = LayoutOptions.Fill,
HorizontalOptions = LayoutOptions.FillAndExpand,
BackgroundColor = Color.Transparent,
Opacity = 0.7,
}, 0, 2);
StackLayout ImageLabelContainer = new StackLayout();
Image imgBox = new Image();
imgBox.Source = "scan_qr.png";
imgBox.VerticalOptions = LayoutOptions.Fill;
imgBox.HorizontalOptions = LayoutOptions.FillAndExpand;
ImageLabelContainer.Children.Add(imgBox);
Label lblSuccess = new Label();
lblSuccess.Margin = new Thickness(0, 7, 0, 0);
lblSuccess.HorizontalTextAlignment = TextAlignment.Center;
lblSuccess.TextColor = Color.Green;
lblSuccess.AutomationId = "zxingDefaultOverlay_BottomTextLabel";
lblSuccess.SetBinding(Label.TextProperty, new Binding(nameof(BottomText)));
ImageLabelContainer.Children.Add(lblSuccess);
Children.Add(ImageLabelContainer, 0, 1);
}
Here you can set height of the rows as per your requirement.

How to implement method of sub item of DataTemplate of ListView in Xamarin.Forms

I have ListView and I assigned DataTemplate to it. Now I have some controls in it like Button, Images and Labels. Now I want some actions on click event of that controls.
My ListView is like this-
listof_ingredients_and_lifestyleDiets = new ListView
{
BackgroundColor = Color.FromHex ("#CDBA96"),
ItemTemplate = preferenceTableCell,
SeparatorColor =Color.FromHex("#CDBA96"),
RowHeight=40,
HeightRequest=200
};
My DataTemplate is like this-
DataTemplate preferenceTableCell = new DataTemplate (() => {
var itemName = new Label {
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
WidthRequest=80,
FontSize=14,
TextColor=ColorResources.TextColor,
};
itemName.SetBinding (Label.TextProperty, "Name");
var radiobtn_allergen = new CircleImage {
BorderColor = ColorResources.commonButtonBackgroundColor,
HeightRequest = 25,
WidthRequest = 25,
Aspect = Aspect.AspectFill,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
Source="radio_Check.png"
};
radiobtn_allergen.SetBinding(CircleImage.IsVisibleProperty,"isExcluded");
var radiobtn_preference = new CircleImage {
BorderColor = ColorResources.commonButtonBackgroundColor,
HeightRequest = 25,
WidthRequest = 25,
Aspect = Aspect.AspectFill,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
Source="radio_uncheck.png",
};radiobtn_preference.SetBinding (CircleImage.IsVisibleProperty, "isExcluded");
var btnDelete=new Button{
Image="deleteBtn.png",
HorizontalOptions=LayoutOptions.EndAndExpand,
HeightRequest=50,
WidthRequest=30
};
StackLayout stacklayout = new StackLayout {
Spacing = 60,
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { itemName,radiobtn_allergen,radiobtn_preference,btnDelete }
};
return new ViewCell { View = stacklayout };
});
Now My question is, I want implement tap gesture for image tap and button click event for button control. How to do this?
Click handler for a button
btnDelete.Clicked += ((sender, args) => {
// perform actions here
});
attach a gesture recognizer to an Image
TapGestureRecognizer tapped = new TapGestureRecognizer();
tapped.Tapped += ((o2, e2) =>
{
// perform actions here
});
img.GestureRecognizers.Add(tapped);

Button on top of the Scrollview does not show up

I have something like this so far for my view:
public StackLayout OffersSlideViewCarouselChild(Offer offer)
{
Image productImage = new Image
{
Source = ImageSource.FromUri(new Uri(offer.Image.Replace("https://", "http://"))),
HeightRequest = 270,
WidthRequest = 270,
Aspect = Aspect.AspectFit
};
var topStackLayout = new StackLayout
{
Spacing = 0
};
topStackLayout.Children.Add(productImage);
StackLayout contentStackLayout = new StackLayout
{
Spacing = 0,
Padding = new Thickness(5, 10, 5, 10),
Orientation = StackOrientation.Vertical
};
var savedBtn = SavedButtonLayout(offer.IsSelected, offer.Id);
var redeemBtn = RedeemBtnLayout(offer.Id);
var timeRemainingLabel = TimeRemainingLayout(offer, offer.Id);
contentStackLayout.Children.Add(new UILabel(16) {
Text = offer.ProductName,
TextColor = ColorHelper.FromHex(CoreTheme.COLOR_OFFERCELL_PRODUCT_TEXT),
FontFamily = CoreTheme.FONT_FAMILY_DEFAULT_BOLD,
WidthRequest = DeviceDisplaySettings.defaultwidth,
VerticalTextAlignment = TextAlignment.Center
});
contentStackLayout.Children.Add(new UILabel(14)
{
Text = offer.Headline,
TextColor = ColorHelper.FromHex(CoreTheme.COLOR_OFFERCELL_PRODUCT_TEXT),
FontFamily = CoreTheme.FONT_FAMILY_DEFAULT_BOLD,
WidthRequest = DeviceDisplaySettings.defaultwidth,
VerticalTextAlignment = TextAlignment.Center
});
contentStackLayout.Children.Add(new UILabel(14) {
Text = offer.LongRewardsMessage,
TextColor = ColorHelper.FromHex(CoreTheme.COLOR_DEAL_PAGE_LONG_REWARD_MESSAGE_RED),
FontFamily = CoreTheme.FONT_FAMILY_DEFAULT_BOLD,
WidthRequest = DeviceDisplaySettings.defaultwidth,
VerticalTextAlignment = TextAlignment.Center
});
if (!string.IsNullOrEmpty(offer.PowerMessage)) {
var htmlText = string.Format("<html><body style='color:#9b9b9b'>{0}</body></html>", offer.PowerMessage.Replace(#"\", string.Empty));
var browser = new WebView() {
//HeightRequest = (DeviceDisplaySettings.defaultheight > 600) ? 500 : 400,
HeightRequest = 800,
Source = new HtmlWebViewSource() { Html = htmlText },
};
browser.Navigating += OnNavigating;
contentStackLayout.Children.Add(browser);
}
var nestedStackLayout = new StackLayout()
{
VerticalOptions = LayoutOptions.FillAndExpand
};
nestedStackLayout.Children.Add(topStackLayout);
nestedStackLayout.Children.Add(timeRemainingLabel);
nestedStackLayout.Children.Add(contentStackLayout);
var mainScrollView = new ScrollView()
{
Padding = new Thickness(0, 0, 0, 10),
VerticalOptions = LayoutOptions.FillAndExpand,
Orientation = ScrollOrientation.Vertical,
Content = nestedStackLayout
};
var mainStackLayout = new StackLayout()
{
Spacing = 5,
Padding = new Thickness(0, 0, 0, 0),
VerticalOptions = LayoutOptions.Fill,
HorizontalOptions = LayoutOptions.Fill,
Orientation = StackOrientation.Vertical,
Children = { savedBtn, mainScrollView, redeemBtn }
};
return mainStackLayout;
}
private StackLayout SavedButtonLayout(bool isSelected, int offerid)
{
int buttonsToShow = 2;
bool displaySaveButton = true;
if (IsPremisesOffer (offerid)) {
buttonsToShow = 3;
displaySaveButton = false;
}
btnShare = new UIFieldDefinition(_pageFieldDefinition.ShareButtonDefinition);
btnShare.Text = "SHARE";
btnShare.ClassId = offerid.ToString();
btnShare.WidthRequest = (DeviceDisplaySettings.defaultwidth / buttonsToShow) - 40;
btnShare.BackgroundColor = Color.FromRgb(167, 188, 33);
btnShare.VerticalContentAlignment = TextAlignment.Center;
btnShare.HandleClick(btnShare_Clicked);
btnSave = new UIFieldDefinition(_pageFieldDefinition.SaveButtonDefinition);
btnSave.Text = isSelected ? "UNSAVE" : "SAVE";
btnSave.ClassId = offerid.ToString();
btnSave.WidthRequest = (DeviceDisplaySettings.defaultwidth / buttonsToShow) - 40;
btnSave.BackgroundColor = Color.FromRgb(167, 188, 33);
btnSave.VerticalContentAlignment = TextAlignment.Center;
btnSave.HandleClick(btnSave_Clicked);
rl = new StackLayout {
Spacing = 10,
Orientation = StackOrientation.Horizontal,
BackgroundColor = Color.FromRgb(196, 221, 57),
Padding = new Thickness(40, 5, 5, 5),
WidthRequest = DeviceDisplaySettings.defaultwidth
};
rl.Children.Add(btnShare);
if (displaySaveButton) rl.Children.Add(btnSave);
return rl;
}
public UIFieldDefinition RedeemBtnLayout(int offerid)
{
int buttonsToShow = 1;
btnRedeem = new UIFieldDefinition(_pageFieldDefinition.RedeemButtonDefinition);
btnRedeem.Text = "REDEEM NOW";
btnRedeem.ClassId = offerid.ToString();
btnRedeem.WidthRequest = (DeviceDisplaySettings.defaultwidth / buttonsToShow) - 10;
// btnRedeem.HorizontalOptions = LayoutOptions.FillAndExpand;
// btnRedeem.VerticalOptions = LayoutOptions.EndAndExpand;
btnRedeem.HandleClick(btnRedeem_Clicked);
return btnRedeem;
}
However, I am noticing that the Redeem button does not even display on the view (It's supposed to be fixed on the bottom).
The scrollview works but the buttom is missing. Why?
Please let me know if you need further code details.
Moving here from comments above. There are two separate issues from what I can tell, and as far as I can tell, are unrelated:
The WebView, nested inside the ScrollView, is not big enough to fully display the content.
The button that is supposed to be at the bottom of the screen is not displaying.
For both of them, the answer is probably in how you are setting HeightRequest. There have been a lot of suggestions by myself and other commenters to change or get rid of some of the HeightRequest settings, and I'm not sure of the current state of your source code. So assuming those are still there:
For solving the WebView issue, read How can I add HTML to a Stacklayout inside a Scrollview in Xamarin forms?. This will let you figure out the right HeightRequest to use. The short answer is that depending on exactly what you want to happen, you may need a custom renderer. Note that the HeightRequest for the WebView will not affect any layout outside of the ScrollView.
For solving the issue of the button not appearing, get rid of the HeightRequest setting on the ScrollView, and the VerticalOptions on the StackLayout created in SavedButtonLayout.
I am assuming you did the experiment suggested above to make sure that the redeemBtn will render if placed before the ScrollView, and it does show up then. If not, you first need to fix that.
If you have "fixed" this by changing the HeightRequest then your real problem is the fixed pixel size of all your views and layouts, I recommend you DON'T use fixed pixel sizes for different screen resolution this will be a bigger problem later, What you can do is get the Screen size and do the math to fit all your elements of the view, one way to get the width and height of the screen is on the OnSizeChanged event of Pages (Like ContentPage), something like this:
SizeChanged += SizeChanged;
void SizeChanged (object sender, EventArgs e)
{
Layout.WidthRequest = Width * 0.3;
Layout.HeightRequest = Height * 0.35;
}
Your layout is pretty busy. A few things:
Set VerticalOptions to EndAndExpand for redeemBtn.
Set VerticalOptions to StartAndExpand for savedBtn.
Set VerticalOptions to Fill for mainScrollView.
Set VerticalOptions to FillAndExpand for mainRelLayout.
Set VerticalOptions and HorizontalOptions to Fill for
mainStackLayout.
I think that will get you to where you want to be.
The options that include "Expand" will grow the element to accommodate the desired height of its contents.

Categories

Resources