How I can Add Text inside Frame TabbedRenderer in Xamarin iOS - xamarin.ios

I am customizing Badge in TabbedPage. I have now added the red dot from inheriting UIView. However how can I Add Text inside that Frame. Xamarin iOS
MyTabbedPageRenderer.cs
public static class TabbarExtensions
{
readonly static int tabBarItemTag = 9999;
public static void addItemBadge(this UITabBar tabbar, int index)
{
if (tabbar.Items != null && tabbar.Items.Length == 0) return;
if (index >= tabbar.Items.Length) return;
removeItemBadge(tabbar, index);
var badgeView = new UIView();
badgeView.Tag = tabBarItemTag + index;
badgeView.Layer.CornerRadius = 7;
badgeView.BackgroundColor = UIColor.Red;
var tabFrame = tabbar.Frame;
var percentX = (index + 0.56) / tabbar.Items.Length;
var x = percentX * tabFrame.Width;
var y = tabFrame.Height * 0.05;
badgeView.Frame = new CoreGraphics.CGRect(x, y, 13, 13);
tabbar.AddSubview(badgeView);
//var badgeView = new UILabel();
//badgeView.Tag = tabBarItemTag + index;
//badgeView.BackgroundColor = UIColor.Red;
//var tabFrame = tabbar.Frame;
//var percentX = (index + 0.56) / tabbar.Items.Length;
//var x = percentX * tabFrame.Width;
//var y = tabFrame.Height * 0.05;
//badgeView.Text = "1";
//badgeView.TextAlignment = UITextAlignment.Center;
//badgeView.TextColor = UIColor.White;
//badgeView.Font = UIFont.SystemFontOfSize(10);
//tabbar.AddSubview(badgeView);
}
public static bool removeItemBadge(this UITabBar tabbar, int index)
{
foreach (var subView in tabbar.Subviews)
{
if (subView.Tag == tabBarItemTag + index)
{
subView.RemoveFromSuperview();
return true;
}
}
return false;
}
}
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
MessagingCenter.Subscribe<object, int>(this, "Add", (obj, index) => {
TabBar.addItemBadge(index);
});
MessagingCenter.Subscribe<object, int>(this, "Remove", (obj, index) => {
TabBar.removeItemBadge(index);
});
}
MainView.xaml.cs
protected override void OnAppearing()
{
base.OnAppearing();
MessagingCenter.Send<object, int>(this, "Add", 2);
}
As in my code above I tried with UILabel. However I cannot set CornerRadius for Label
Summarize how I can Add Text inside Frame. Or how can I set CornerRadius for Lable in Xamarin iOS.
Thank you!
Description picture:
If I use UILabel, I cannot set CornerRadius
If I use UIView

For UILabel, you could set the CornerRadius using the following:
badgeView.Layer.CornerRadius = 7;
badgeView.Layer.MasksToBounds = true;//add this line
For more info, you could refer to masksToBounds.
Hope it works for you.

Related

trigger is called in beginning

I have a sound that gets triggered with OnTriggerEnter, and picking up whether sound is playing to turn sprite renderer on/off.
For some reason, when I start the game, the sound starts playing (which should only be getting called by the trigger).
I checked the trigger with the players tag and debug.log to console, and found that the trigger method isn't being called at the start. But, for some reason, the sound is getting played at the start and when I hit the trigger(but not turning the sprite renderer back on).
FlagScript
#pragma strict
var Sprite2 : Sprite; //second sprite to renderer
var sr : SpriteRenderer;
var hasBeenHit : boolean = false;
var flagCollisionSounderies: AudioSource;
var flagCollisionSound : AudioClip = null;
private var applauseRef: ApplauseScript;
private var go: GameObject;
var count : int = 0;
function Start () {
//access the spriteRenderer
flagCollisionSound = flagCollisionSounderies.clip;
sr = GetComponent(SpriteRenderer);
go = GameObject.Find("ClapMaster");
applauseRef = go.GetComponent(typeof(ApplauseScript));
//Debug.Log("bool: "+flagCollisionSounderies.isPlaying); //true already
}
function OnTriggerEnter2D(coll: Collider2D){
//Debug.Log("flagtriggered");
//change the flag to other flag
sr.sprite = Sprite2;
if (coll.gameObject.tag == "Player"){
Debug.Log("poos");
if (hasBeenHit == false){
GameMaster.setFlags(GameMaster.getFlags()-1);
GameMaster.addPointsToScore(100);
if (flagCollisionSound != null){
flagCollisionSounderies.PlayClipAtPoint(flagCollisionSound, transform.position);
//Debug.Log("bool:" + flagCollisionSounderies.isPlaying);
applauseRef.animRenderer.enabled = true;
}
}
}
hasBeenHit = true;
}
function Update(){
if(!flagCollisionSounderies.isPlaying){
applauseRef.animRenderer.enabled = false;
//applauseRef.playApplauseAnim = false;
}else{
//Debug.Log("sounderies detecteddFsdlfkjsdlfksjdflksdjflkj1123123");
applauseRef.animRenderer.enabled = true;
//applauseRef.playApplauseAnim = true;
}
}
Applause Script
#pragma strict
var SpriteLoad: Sprite[];
static var animSprites : Sprite[];
static var playerScriptRef: newplayer;
static var animRenderer: SpriteRenderer;
//private static var i : int = 7;
private static var frame : int = 3;
private static var Ymove: float = 0f;
private static var goingUp: boolean = false;
static var playApplauseAnim: boolean;
function Start(){
animRenderer = GetComponent(SpriteRenderer);
animSprites = SpriteLoad;
playerScriptRef = GameObject.Find("Player 1").GetComponent(newplayer);
//animRenderer.enabled = false;
//playApplauseAnim = false;
}
function Update(){
PicMover();
frame = (frame +1 ) % 4;
animRenderer.sprite = animSprites[frame];
}
static function PicMover(){
if(Ymove < 20 && goingUp){
Ymove++;
}else if(Ymove > -20 && !goingUp){
Ymove--;
}else if(Ymove == 20){
goingUp = false;
}else if(Ymove == -20){
goingUp = true;
}
animRenderer.transform.position = new Vector2(10,10);
}

MvvmCross: Cannot add more than one UIPickerView

I'm building an iOS view using Xamarin and MvvmCross and I have come across an interesting little issue. I can't seem to add more than one UIPickerView to a UIView.
Add one view and all works well. Add a second and the simulator just hangs when I try and open the page.
This seems to be related to a UITextField with an InputView as I also have an issue if I try to add a UIDatePicker as well.
Nothing strange in the debug output.
Here is the code:
[Register("EditJobViewJobView")]
public class EditJobView : MvxViewController
{
public new EditJobViewModel ViewModel
{
get { return (EditJobViewModel)base.ViewModel; }
}
private const float _leftMargin = 6;
private const float _labelHeight = 20;
private const float _pickerHeight = 28;
private readonly UIFont _labelFont = UIFont.BoldSystemFontOfSize(18f);
private readonly UIFont _controlFont = UIFont.SystemFontOfSize(18f);
private readonly UIView _paddingInsert = new UIView(new RectangleF(0, 0, 4, 0));
private int _currentTop = 0;
public override void ViewDidLoad()
{
base.ViewDidLoad();
View = new UIView() { BackgroundColor = UIColor.White };
NavigationItem.SetRightBarButtonItem(new UIBarButtonItem("Save", UIBarButtonItemStyle.Bordered,
(sender, args) => ViewModel.OkCommand.Execute(null)), true);
// ios7 layout
if (RespondsToSelector(new Selector("edgesForExtendedLayout")))
EdgesForExtendedLayout = UIRectEdge.None;
Title = "Edit Job";
AddLabel("Job Status");
MvxPickerViewModel jobStatusPickerViewModel;
var jobStatusTextView = AddPickerView(out jobStatusPickerViewModel);
AddLabel("Job Priority");
MvxPickerViewModel jobPriorityPickerViewModel;
var jobPriorityTextView = AddPickerView(out jobPriorityPickerViewModel);
var set = this.CreateBindingSet<EditJobView, EditJobViewModel>();
set.Bind(jobStatusPickerViewModel).For(p => p.SelectedItem).To(vm => vm.SelectedJobStatusType);
set.Bind(jobStatusPickerViewModel).For(p => p.ItemsSource).To(vm => vm.JobStatusTypes);
set.Bind(jobStatusTextView).To(vm => vm.SelectedJobStatusType);
set.Bind(jobPriorityPickerViewModel).For(p => p.SelectedItem).To(vm => vm.SelectedJobPriority);
set.Bind(jobPriorityPickerViewModel).For(p => p.ItemsSource).To(vm => vm.JobPriorities);
set.Bind(jobPriorityTextView).To(vm => vm.SelectedJobPriority);
set.Apply();
}
private void AddLabel(string caption)
{
_currentTop += 10;
var frame = new RectangleF(_leftMargin, _currentTop, 300, _labelHeight);
var label = new UILabel(frame);
label.Font = _labelFont;
label.Text = caption;
AddView(label);
_currentTop += 2;
}
private UITextField AddPickerView(out MvxPickerViewModel pickerViewModel)
{
var textField = AddTextField();
var pickerView = new UIPickerView();
pickerViewModel = new MvxPickerViewModel(pickerView);
pickerView.Model = pickerViewModel;
pickerView.ShowSelectionIndicator = true;
textField.InputView = pickerView;
return textField;
}
private UITextField AddTextField()
{
var frame = new RectangleF(_leftMargin, _currentTop, 300, _pickerHeight);
var textField = new UITextField(frame);
textField.Layer.BorderColor = UIColor.Black.CGColor;
textField.Layer.BorderWidth = 1f;
textField.Font = _controlFont;
textField.LeftView = _paddingInsert;
textField.LeftViewMode = UITextFieldViewMode.Always;
AddView(textField);
return textField;
}
private void AddView(UIView view)
{
View.AddSubview(view);
_currentTop += (int)view.Frame.Height;
}
}
Any ideas?
This was caused by creating a shared padding insert across a number of UITextFields.
To fix this I changed
textField.LeftView = _paddingInsert;
to
textField.LeftView = new UIView(new RectangleF(0, 0, 4, 0));

How to add text and image in a column in Component One FlexGrid?

I have used the below mentioned snippet to show text with image. However I am unable to display image with it.
Is the path to image not accessible from code?
C1.Win.C1FlexGrid.C1FlexGrid gAuditL = new C1.Win.C1FlexGrid.C1FlexGrid();
.
.
.
gAuditL.DataSource = AuditLogVieweryDT;// this is datasource
for (int i = gAuditL.Row.Fixed; i < gAuditL.Rows.Count; i++)
//foreach row in grid
{
string severity = gAuditL[i, gAuditL.Cols["Severity"].Index].ToString();
if (severity == "Information")
{
this.gAuditL.SetCellImage(i, 0,Image.FromFile(#".\\Resources\information.bmp"));
this.gAuditL.SetData(i, 0, "Information");
}
if (severity == "Warning")
{
this.gAuditL.SetCellImage(i, 0, Image.FromFile(#".\\Resources\warning.bmp"));
this.gAuditL.SetData(i, 0, "Warning");
}
if (severity == "Critical")
{
this.gAuditL.SetCellImage(i, 0, Image.FromFile(#".\\Resources\critical.bmp"));
this.gAuditL.SetData(i, 0, "Critical");
}
if (severity == "Unspecified")
{
this.gAuditL.SetCellImage(i, 0, Image.FromFile(#".\\Resources\unspecified.bmp"));
this.gAuditL.SetData(i, 0, "Unspecified");
}
this.gAuditL.Styles.Normal.ImageAlign = C1.Win.C1FlexGrid.ImageAlignEnum.LeftCenter;
this.gAuditL.Styles.Normal.TextAlign = C1.Win.C1FlexGrid.TextAlignEnum.RightCenter;
}
Please refer this.(Answer posted by OP)
namespace SampleProject.Forms.Maintenance
{
public partial class SampleProject: Form
{
Image img1, img2, img3, img4;// declare member variable
//Load Event
private void AuditLogViewer_Load(object sender, EventArgs e)
{
object information = Resources.ResourceManager.GetObject("information"); //Return an object from the image chan1.png in the project
img1 = (Image)information;
object Warning = Resources.ResourceManager.GetObject("warning"); //Return an object from the image chan1.png in the project
img2 = (Image)Warning;
object critical = Resources.ResourceManager.GetObject("critical"); //Return an object from the image chan1.png in the project
img3 = (Image)critical;
object unspecified = Resources.ResourceManager.GetObject("unspecified"); //Return an object from the image chan1.png in the project
img4 = (Image)unspecified;
}
//Grid Click Event
private void grdAuditLogs_OwnerDrawCell(object sender, OwnerDrawCellEventArgs e)
{
if (e.Col == 2)
{
//let the grid paint the background and border for the cell
e.DrawCell(C1.Win.C1FlexGrid.DrawCellFlags.Background | C1.Win.C1FlexGrid.DrawCellFlags.Border);
//find text width
var width = (int)e.Graphics.MeasureString(e.Text, e.Style.Font).Width;
//x-coordinate for each image
var img1_x = e.Bounds.X + width + 10;
var img2_x = e.Bounds.X + width + 10;
var img3_x = e.Bounds.X + width + 10;
var img4_x = e.Bounds.X + width + 10;
//var img3_x = img2_x + img2.Width + 5;
//location for each image
var img1_loc = new Point(img1_x, e.Bounds.Y + img1.Height - 18);
var img2_loc = new Point(img2_x, e.Bounds.Y + img2.Height - 18);
var img3_loc = new Point(img3_x, e.Bounds.Y + img3.Height - 18);
var img4_loc = new Point(img4_x, e.Bounds.Y + img4.Height - 18);
//draw images at aforementioned points
if (grdAuditLogs[e.Row, grdAuditLogs.Cols["Severity"].Index].ToString() == "Information")
e.Graphics.DrawImage(img1, img1_loc);
if (grdAuditLogs[e.Row, grdAuditLogs.Cols["Severity"].Index].ToString() == "Warning")
e.Graphics.DrawImage(img2, img2_loc);
if (grdAuditLogs[e.Row, grdAuditLogs.Cols["Severity"].Index].ToString() == "Critical")
e.Graphics.DrawImage(img3, img3_loc);
if (grdAuditLogs[e.Row, grdAuditLogs.Cols["Severity"].Index].ToString() == "Unspecified")
e.Graphics.DrawImage(img4, img4_loc);
//e1.Graphics.DrawImage(img3, img3_loc);
//draw text
e.Graphics.DrawString(e.Text, e.Style.Font, Brushes.Black, e.Bounds.Location);
e.Handled = true;
}
}

Array of Images

I'm working on a blackberry project and for that I need to create grid layout. I'm working on "Blackberry java sdk".
I'm using this code
public class GridScreen extends UiApplication {
// main method
public static void main(String[] args) {
GridScreen theApp = new GridScreen();
UiApplication.getUiApplication().pushScreen(new GFMScreen());
theApp.enterEventDispatcher();
}
}
// VFM
class GFMScreen extends MainScreen {
public GFMScreen() {
// this doesnt do anything for VCENTER!!
//super(Field.USE_ALL_HEIGHT);
// create a grid field manager, with 2 cols and 0 style param for super class
// style of Manager.FIELD_VCENTER | Field.USE_ALL_HEIGHT doesnt do a thing!
int columns = 2;
final GridFieldManager gfm = new GridFieldManager(columns, 0);
// add some items to the screen
int size = 6;
BitmapField[] fRay = new BitmapField[size];
for (int i = 0; i < size; i++) {
// create an bitmap field that's centered H + V (inside grid space)
fRay[i] = new BitmapField(loadBitmap("images/" + (i + 1) + ".png"),
Field.FIELD_HCENTER | Field.FIELD_VCENTER | Field.FOCUSABLE);
gfm.add(fRay[i]);
}
// set padding on top/bottom
{
// add gfm to screen - this does not center the gfm on the screen... is top aligned no matter what!
add(gfm);
int gfmHeight = 48 * (size / columns);
int borderHeight = (Display.getHeight() - gfmHeight) / 2;
gfm.setBorder(BorderFactory.createSimpleBorder(
new XYEdges(borderHeight, 0, borderHeight, 0),
Border.STYLE_TRANSPARENT));
System.out.println("border=" + borderHeight);
System.out.println("display=" + Display.getHeight());
System.out.println("gfm=" + gfmHeight);
}
}
/** #param res eg "images/icon.png" */
public static Bitmap loadBitmap(String res) {
EncodedImage img = EncodedImage.getEncodedImageResource(res);
return img.getBitmap();
}
}// end class
What is wrong in this code?
Is there any best approch to create grid layout in BlackBerry.
In above code error is "Display.getHeight() is not define".
Hope this code helps:
Bitmap[] images = new Bitmap[6];
for ((int i = 0; i < 6; i++) {
string filename = "images/" + String.valueOf(i + 1) + ".png";
images[i] = Bitmap.getBitmapResource(filename);
}
}

Creating Tabmenu in j2me

Is there any way to create a Tab Menu in j2me?
I found a code but I am unable to understand it
In this code there is Tab Menu created which is in Canvas class and then Tab menu is created which is totally done in Canvas or painted. The only part I found difficult to grasp was the void go() method and then
When I try to draw anything above and below this code using paint method, it doesn't work - what's the problem?
Below is the code
// Tab Menu CANVAS class
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
public class TabMenuCanvas extends Canvas
{
TabMenu menu = null;
public TabMenuCanvas()
{
menu = new TabMenu(
new String[]{"Home", "News", "Community", "Your files", "Credits", "Events", "Blog", "Upload", "Forum Nokia"},
getWidth() - 20
);
}
protected void keyPressed(int key)
{
int gameAction = getGameAction(key);
if(gameAction == Canvas.RIGHT)
{
menu.goRight();
repaint();
}
else if(gameAction == Canvas.LEFT)
{
menu.goLeft();
repaint();
}
}
protected void paint(Graphics g)
{
g.translate(10, 30);
menu.paint(g);
g.translate(- 10, - 30);
}
}
// Tab Menu Class
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
public class TabMenu
{
int background = 0xffffff;
int bgColor = 0xcccccc;
int bgFocusedColor = 0x0000ff;
int foreColor = 0x000000;
int foreFocusedColor = 0xffffff;
int cornerRadius = 6;
int padding = 2;
int margin = 2;
Font font = Font.getDefaultFont();
int scrollStep = 20;
int selectedTab = 0; //selected tab index
int[] tabsWidth = null; //width of single tabs
int[] tabsLeft = null; //left X coordinate of single tabs
int tabHeight = 0; //height of tabs (equal for all tabs)
String[] tabs = null; //tab labels
int menuWidth = 0; //total menu width
int viewportWidth = 0; //visible viewport width
int viewportX = 0; //current viewport X coordinate
public TabMenu(String[] tabs, int width)
{
this.tabs = tabs;
this.viewportWidth = width;
initialize();
}
void initialize()
{
tabHeight = font.getHeight() + cornerRadius + 2 * padding; //[ same for all tabs]
menuWidth = 0;
tabsWidth = new int[tabs.length];
tabsLeft = new int[tabs.length];
for(int i = 0; i < tabsWidth.length; i++)
{
tabsWidth[i] = font.stringWidth(tabs[i]) + 2 * padding + 2 * cornerRadius;
tabsLeft[i] = menuWidth;
menuWidth += tabsWidth[i];
if(i > 0)
{
menuWidth += margin;
}
}
}
public void goRight()
{
go(+1);
}
public void goLeft()
{
go(-1);
}
private void go(int delta)
{
int newTab = Math.max(0, Math.min(tabs.length - 1, selectedTab + delta));
boolean scroll = true;
if(newTab != selectedTab && isTabVisible(newTab))
{
selectedTab = newTab;
if( (delta > 0 && tabsLeft[selectedTab] + tabsWidth[selectedTab] > viewportX + viewportWidth) ||
(delta < 0 && tabsLeft[selectedTab] < viewportX))
{
scroll = true;
}
else
{
scroll = false;
}
}
if(scroll)
{
viewportX = Math.max(0, Math.min(menuWidth - viewportWidth, viewportX + delta * scrollStep));
}
}
private boolean isTabVisible(int tabIndex)
{
return tabsLeft[tabIndex] < viewportX + viewportWidth &&
tabsLeft[tabIndex] + tabsWidth[tabIndex] >= viewportX;
}
public void paint(Graphics g)
{
int currentX = - viewportX;
g.setClip(0, 0, viewportWidth, tabHeight);
g.setColor(background);
g.fillRect(0, 0, viewportWidth, tabHeight);
for(int i = 0; i < tabs.length; i++)
{
g.setColor(i == selectedTab ? bgFocusedColor : bgColor);
g.fillRoundRect(currentX, 0, tabsWidth[i], tabHeight + cornerRadius, 2 * cornerRadius, 2 * cornerRadius);
g.setColor(i == selectedTab ? foreFocusedColor : foreColor);
g.drawString(tabs[i], currentX + cornerRadius + padding, cornerRadius + padding, Graphics.LEFT | Graphics.TOP);
currentX += tabsWidth[i] + margin;
}
}
}
When I try to draw anything above and below this code using paint method, it doesn't work
what of the paint methods you use to draw above and below? Pay attention that there are two methods named that way - first is in TabMenuCanvas, second is in TabMenu (second method is invoked from TabMenuCanvas#repaint).
whatever you would try to draw in TabMenuCanvas#paint will most likely be overwritten by setClip and fillRect when TabMenu#paint is invoked following repaint request
The only place where one can expect to be able to draw something visible seems to be in TabMenu#paint method, inside the clip area that is set there.
You can use GUI Libraries for J2ME,for example Lightweight User Interface Toolkit (LWUIT),Flemil have "tab menu".You can see list of GUI Libraries here.

Resources