How to use UIStepper in Monotouch - xamarin.ios

How to use UIStepper Control in an IOS Application. I am using monotouch, C# and examples i have seen are not of c#. the following code doesn't show anything.
UIStepper stepper = new UIStepper();
var section = new Section();
section.Add(stepper);

This should get you going:
var stepper = new UIStepper(new RectangleF(50, 50, 100, 50));
stepper.MinimumValue = 0;
stepper.MaximumValue = 10;
View.AddSubview(stepper);
stepper.ValueChanged += (object sender, EventArgs e) => Console.WriteLine(stepper.Value);

Related

iOS 13 Changes to UISearchBar tint's, can't achieve the same outcome

I've been experimenting all day and trying to figure out just how to get my UISearchBar to appear the same in iOS13 as it appears in iOS12/11
So the way the search bar is added is simply a new UISearchController.
var searchController = new UISearchController(searchResultsController: null);
searchController.SearchBar.Placeholder = "Search";
searchController.SearchResultsUpdater = this;
searchController.HidesNavigationBarDuringPresentation = false;
searchController.DimsBackgroundDuringPresentation = false;
NavigationItem.SearchController = searchController;
NavigationItem.HidesSearchBarWhenScrolling = false;
The results on iOS 11/12:
The results on iOS 13:
On iOS 13 I am using the new UINavigationBarAppearance code like this:
var appearance = new UINavigationBarAppearance();
appearance.ConfigureWithOpaqueBackground();
appearance.BackgroundColor = ColorPalette.TintColor;
appearance.TitleTextAttributes = new UIStringAttributes { ForegroundColor = UIColor.White };
NavigationItem.StandardAppearance = appearance;
On iOS 11/12 I am using legacy way to achieve it:
NavigationController.NavigationBar.BarStyle = UIBarStyle.Black;
NavigationController.NavigationBar.TintColor = UIColor.White;
NavigationController.NavigationBar.BarTintColor = ColorPalette.TintColor;
NavigationController.NavigationBar.Translucent = false;
I've tried a number of things, but can't seem to get the UISearchBar to tint by itself how iOS11/12 achieves it.
I know that the new UISearchBar now has access to the UITextField and I can configure the background color's etc.
searchBar.setSearchFieldBackgroundImage(UIImage(), for: .normal)
The code above has a side effect which removes corner radius of the text field.
Extension
extension UISearchBar {
  /// This solves iOS 13 issue which is a light gray overay covers the textField.
  /// - Parameter color: A color for searchField
  func setSearchFieldBackgroundColor(_ color: UIColor) {
    searchTextField.backgroundColor = color
    setSearchFieldBackgroundImage(UIImage(), for: .normal)
    // Make up the default cornerRadius changed by `setSearchFieldBackgroundImage(_:for:)`
    searchTextField.layer.cornerRadius = 10
    searchTextField.clipsToBounds = true
  }
}
There were several properties added in iOS 13, so you need to use them with the help of a conditional. For changing the background color, you have to use the BackgroundColor property of the SearchBar, like this
searchController.SearchBar.BackgroundColor = UIColor.Red;
Use a custom renderer and override the OnElementChanged method this way
protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
{
base.OnElementChanged(e);
if (Control != null)
{
if(UIDevice.CurrentDevice.CheckSystemVersion(13,0))
Control.SearchTextField.BackgroundColor = Element.BackgroundColor.ToUIColor();
}
}
later on, you don't have to do anything else and worked for me on ios 12 and ios 13+
On iOS 13, you have access to the internal UISearchTextField through the SearchTextField property, you can set it's background directly (in my case, I need the background to be white). Be sure to check the iOS version to avoid exceptions.
if(UIDevice.CurrentDevice.CheckSystemVersion(13,0))
{
searchController.SearchBar.SearchTextField.BackgroundColor = UIColor.White;
}
You can achieve desired result by adding couple of lines.
searchBar.barTintColor = UIColor.red
searchBar.searchTextField.backgroundColor = UIColor.white
Before you try this code please link IB Outlets for searchBar
#IBOutlet weak var searchBar: UISearchBar!

applicationData.current.localFolder.CreateFileQueryWithOptions(queryOptions); don't work

I excerpt from windows 8.1 sample of StorageDataSource and GetVirtualizedFilesVector sample a piece of code in my project can run successfully, but I changed to this: From ApplicationData.current.localFolder the deposit into my pictures do not show up success
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var queryOptions = new QueryOptions();
queryOptions.FolderDepth = FolderDepth.Deep;
queryOptions.IndexerOption = IndexerOption.UseIndexerWhenAvailable;
queryOptions.SortOrder.Clear();
var sortEntry = new SortEntry();
sortEntry.PropertyName = "System.FileName";
sortEntry.AscendingOrder = true;
queryOptions.SortOrder.Add(sortEntry);
//var fileQuery = KnownFolders.PicturesLibrary.CreateFileQueryWithOptions(queryOptions);
var fileQuery = ApplicationData.Current.LocalFolder.CreateFileQueryWithOptions(queryOptions);
const uint size = 400; // default size for PicturesView mode
var fileInformationFactory = new FileInformationFactory(fileQuery, ThumbnailMode.PicturesView, size, ThumbnailOptions.UseCurrentScale, true);
itemsViewSource.Source = fileInformationFactory.GetVirtualizedFilesVector();
}
Commented that the original sample code, comments, following the line of code that I want to be able to run.
thanks a lot!
Do you have accessright for picture library?
To do the programatic access like your code, The app should have it.
You can on/off it from Package.appxmanifest.

How can I grayscale a emf image

Using C# and Visual Studio 2010, how can I make a grayscaled emf from a colored one? Should I enumerate records and change color settings somehow?
As a result I want to have a new emf image.
Here is an open source emf read/write utility. I don't think it can be done with GDI+ and preserve the vector content. So this hopefully will help you, but I haven't remotely tested all possible emf cases.
https://wmf.codeplex.com/
this works for both wmf and emf formats. We can combine the Oxage.Wmf strategy with the strategy from the other post which essentially re-colors a pen or brush when it is created so that anything drawn with that pen or brush should be gray.
using Oxage.Wmf;
using Oxage.Wmf.Records;
using Oxage.Wmf.Objects;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MetafileTest
{
public class GrayMap
{
public void GrayFile(string sourceFile, string destFile){
WmfDocument wmf = new WmfDocument();
wmf.Load(sourceFile);
foreach (var record in wmf.Records)
{
if (record is WmfCreateBrushIndirectRecord)
{
var brush = record as WmfCreateBrushIndirectRecord;
brush.Color = Gray(brush.Color);
}
else if (record is WmfCreatePenIndirectRecord)
{
var pen = record as WmfCreatePenIndirectRecord;
pen.Color = Gray(pen.Color);
}
else if (record is WmfCreatePalette) {
var pal = record as WmfCreatePalette;
foreach (PaletteEntry entry in pal.Palette.PaletteEntries) {
Color test = Color.FromArgb(entry.Red, entry.Green, entry.Blue);
Color grayTest = Gray(test);
entry.Red = grayTest.R;
entry.Green = grayTest.G;
entry.Blue = grayTest.B;
}
}
}
wmf.Save(destFile);
}
public Color Gray(Color original) {
int r = (int)(original.R*0.2989);
int g = (int)(original.G*0.5870);
int b = (int)(original.B*0.1140);
Color result = Color.FromArgb(r, g, b);
return result;
}
}
}
This was tested with the following super simple case of filling a blue rectangle, so for at least the simple cases this will work. It may not be able to handle all cases, but in such a case you can probably extend the original source to suite your needs since it is open source.
private void button1_Click(object sender, EventArgs e)
{
var wmf = new WmfDocument();
wmf.Width = 1000;
wmf.Height = 1000;
wmf.Format.Unit = 288;
wmf.AddPolyFillMode(PolyFillMode.WINDING);
wmf.AddCreateBrushIndirect(Color.Blue, BrushStyle.BS_SOLID);
wmf.AddSelectObject(0);
wmf.AddCreatePenIndirect(Color.Black, PenStyle.PS_SOLID, 1);
wmf.AddSelectObject(1);
wmf.AddRectangle(100, 100, 800, 800);
wmf.AddDeleteObject(0);
wmf.AddDeleteObject(1);
wmf.Save("D:\\test.emf");
}
private void button2_Click(object sender, EventArgs e)
{
GrayMap map = new GrayMap();
map.GrayFile("D:\\test.emf", "D:\\test2.emf");
}

How to make void other thread visit until the code block finished for windows phone animation

I am making a top notification animation, but I don't know how to make the animation synchronous until the animation finishes. Here is the code I have:
public Storyboard prepareShowStory(int count, NotificationControl notifyControl)
{
notifyControl.textBlock1.Text = "Got" + count.ToString() + "Message";
notifyControl.RenderTransform = new CompositeTransform();
Storyboard story = new Storyboard();
//From here until the annimation finish and remove LayoutRoot.Resources.Clear();
LayoutRoot.Resources.Add("unique_id", story);
story.Completed += (object sender, EventArgs e) =>
{
story.Stop();
story.Children.Clear();
App.ViewModel.myAction -= CompletedRefresh;
LayoutRoot.Resources.Clear();
//To here.
};
story.Begin();
DoubleAnimation animation;
animation = new DoubleAnimation();
animation.AutoReverse = true;
animation.From = -64;
animation.To = 60;
animation.Duration = new Duration(TimeSpan.FromMilliseconds(1600));
animation.EasingFunction = _EasingFunction;
Storyboard.SetTargetName(animation, notifyControl.Name);
Storyboard.SetTargetProperty(animation, new PropertyPath("(UIElement.RenderTransform).(CompositeTransform.TranslateY)"));
story.Children.Add(animation);
return story;
}
You could check the ResourceDictionary before adding to it.
if(!LayoutRoot.Resources.Contains("unique_id"))
LayoutRoot.Resources.Add("unique_id", story);

SLIMDX antialising

I try to get the high qulity antialiasing from a tuturial I found on the internet (http://www.rkoenig.eu/index.php?option=com_content&view=article&id=21:chapter-3-das-erste-echte-3d-objekt&catid=6:directx10-basics&Itemid=3). But did not achieve a very good solution.
I already set the multisampling to the maximum:
m_swapChainDesc.SampleDescription = new DXGI.SampleDescription(8,0);
To me it appears as the pixel size of the rendered image is larger than the actual pixel size of my screen.
Thank you very much in advance for your valuable inputs
here is the complete code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SlimDX;
using DX10 = SlimDX.Direct3D10;
using DXGI = SlimDX.DXGI;
namespace TutorialSeries.DirectX10.Chapter3
{
public partial class MainWindow : Form
{
private DX10.Device m_device;
private DXGI.SwapChainDescription m_swapChainDesc;
private DXGI.SwapChain m_swapChain;
private DXGI.Factory m_factory;
private DX10.RenderTargetView m_renderTarget;
private bool m_initialized;
private SimpleBox m_simpleBox;
private Matrix m_viewMatrix;
private Matrix m_projMatrix;
private Matrix m_worldMatrix;
private Matrix m_viewProjMatrix;
public MainWindow()
{
InitializeComponent();
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.Opaque, true);
}
/// <summary>
/// Initializes device and other resources needed for rendering. Returns true, if successful.
/// </summary>
private bool Initialize3D()
{
try
{
m_device = new DX10.Device(DX10.DriverType.Warp, DX10.DeviceCreationFlags.SingleThreaded);
m_factory = new DXGI.Factory();
m_swapChainDesc = new DXGI.SwapChainDescription();
m_swapChainDesc.OutputHandle = this.Handle;
m_swapChainDesc.IsWindowed = true;
m_swapChainDesc.BufferCount = 1;
m_swapChainDesc.Flags = DXGI.SwapChainFlags.AllowModeSwitch;
m_swapChainDesc.ModeDescription = new DXGI.ModeDescription(
this.Width,
this.Height,
new Rational(60, 1),
DXGI.Format.R8G8B8A8_UNorm);
m_swapChainDesc.SampleDescription = new DXGI.SampleDescription(8,0);
m_swapChainDesc.SwapEffect = DXGI.SwapEffect.Discard;
m_swapChainDesc.Usage = DXGI.Usage.RenderTargetOutput;
m_swapChain = new DXGI.SwapChain(m_factory, m_device, m_swapChainDesc);
DX10.Viewport viewPort = new DX10.Viewport();
viewPort.X = 0;
viewPort.Y = 0;
viewPort.Width = this.Width;
viewPort.Height = this.Height;
viewPort.MinZ = 0f;
viewPort.MaxZ = 1f;
//DX10.Texture2D backBuffer = m_swapChain.GetBuffer<DX10.Texture2D>(0);
DX10.Texture2D Texture = DX10.Texture2D.FromSwapChain<DX10.Texture2D>(m_swapChain,0);
//m_renderTarget = new DX10.RenderTargetView(m_device, backBuffer);
//DX10.RenderTargetViewDescription renderDesc = new DX10.RenderTargetViewDescription();
//renderDesc.FirstArraySlice = 0;
//renderDesc.MipSlice = 0;
m_renderTarget = new DX10.RenderTargetView(m_device, Texture);
Texture.Dispose();
DX10.RasterizerStateDescription rsd = new DX10.RasterizerStateDescription();
rsd.CullMode = DX10.CullMode.Back;
rsd.FillMode = DX10.FillMode.Wireframe;
rsd.IsMultisampleEnabled = true;
rsd.IsAntialiasedLineEnabled = false;
rsd.IsDepthClipEnabled = false;
rsd.IsScissorEnabled = false;
DX10.RasterizerState RasterStateWireFrame = DX10.RasterizerState.FromDescription(m_device,rsd);
DX10.BlendStateDescription blendDesc = new DX10.BlendStateDescription();
blendDesc.BlendOperation = DX10.BlendOperation.Add;
blendDesc.AlphaBlendOperation = DX10.BlendOperation.Add;
blendDesc.SourceAlphaBlend = DX10.BlendOption.Zero;
blendDesc.DestinationAlphaBlend = DX10.BlendOption.Zero;
blendDesc.SourceBlend = DX10.BlendOption.SourceColor;
blendDesc.DestinationBlend = DX10.BlendOption.Zero;
blendDesc.IsAlphaToCoverageEnabled = false;
blendDesc.SetWriteMask(0, DX10.ColorWriteMaskFlags.All);
blendDesc.SetBlendEnable(0, true);
DX10.BlendState m_blendState = DX10.BlendState.FromDescription(m_device, blendDesc);
m_device.Rasterizer.State = RasterStateWireFrame;
m_device.Rasterizer.SetViewports(viewPort);
m_device.OutputMerger.BlendState = m_blendState;
m_device.OutputMerger.SetTargets(m_renderTarget);
m_viewMatrix = Matrix.LookAtLH(
new Vector3(0f, 0f, -4f),
new Vector3(0f, 0f, 1f),
new Vector3(0f, 1f, 0f));
m_projMatrix = Matrix.PerspectiveFovLH(
(float)Math.PI * 0.5f,
this.Width / (float)this.Height,
0.1f, 100f);
m_viewProjMatrix = m_viewMatrix * m_projMatrix;
m_worldMatrix = Matrix.RotationYawPitchRoll(0.85f, 0.85f, 0f);
m_simpleBox = new SimpleBox();
m_simpleBox.LoadResources(m_device);
m_initialized = true;
}
catch (Exception ex)
{
MessageBox.Show("Error while initializing Direct3D10: \n" + ex.Message);
m_initialized = false;
}
return m_initialized;
}
/// <summary>
/// Rendering is done during the standard OnPaint event
/// </summary>
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (m_initialized)
{
m_device.ClearRenderTargetView(m_renderTarget, new Color4(Color.CornflowerBlue));
m_simpleBox.Render(m_device, m_worldMatrix, m_viewProjMatrix);
m_swapChain.Present(0, DXGI.PresentFlags.None);
}
}
/// <summary>
/// Initialize 3D-Graphics within OnLoad event
/// </summary>
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Initialize3D();
}
}
}
This is an old question but it's a shame it never got answered; I stumbled across it on Google so I figure answering it may help someone else in the future...
First of all, Pascal, you did NOT set MSAA to the maximum... You're using 8:0, which means 8 samples at a quality of 0 (zero)... definitely not the maximum. What the "max" is depends on the GPU installed on the local machine. So it varies from PC to PC. That's why a DirectX application needs to use DXGI to properly enumerate hardware devices and determine what settings are valid. This is no trivial topic and will require you to do some research and practice of your own. The DirectX SDK Documentation and samples/tutorials are a great starting place, and there's a lot of other materials to be found online. But on my machine, for instance, my GTX-580 GPU can support 8:16 MSAA (possibly higher, but haven't checked).
So you need to learn to use DXGI to enumerate your graphics cards and monitors and figure out what MSAA levels (and other graphics features/settings) it can support. That's the only way you'll ever figure out the "max" MSAA settings or the correct refresh rate of your monitor, for example. If you're clever you will write yourself a small library or component for your game engine that will enumerate hardware devices for you and figure out the optimal graphics settings so you won't have to re-do this over and over for future projects.
Regards,
--ATC--

Resources