protected override void Update(GameTime gameTime) { var metric = new Android.Util.DisplayMetrics(); Activity.WindowManager.DefaultDisplay.GetMetrics(metric); Render.SetScreenInfo(metric); List <Render.Touch> Touches = Render.Recount(TouchPanel.GetState()); switch (State) { case GameState.Menu: startScreen.Update(Touches); if (NeedExit) { Android.OS.Process.KillProcess(Android.OS.Process.MyPid()); } break; case GameState.Load: break; case GameState.Pause: break; case GameState.Game: gameScreen.Update(Touches); break; } }
public static void RefreshFontScale() { using (Android.Util.DisplayMetrics displayMetrics = Android.App.Application.Context.Resources.DisplayMetrics) { _cachedScaledDensity = displayMetrics.ScaledDensity; } }
protected override void OnCreate(Bundle bundle) { AppCenter.Start("2298673e-db16-41c0-aa75-086a6713e52f", typeof(Analytics), typeof(Crashes)); TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; Websockets.Droid.WebsocketConnection.Link(); base.OnCreate(bundle); //pushnotification global::Xamarin.Forms.Forms.Init(this, bundle); //Xamarin.FormsMaps.Init(this, bundle); Xamarin.FormsGoogleMaps.Init(this, bundle); CarouselViewRenderer.Init(); // CrossPushNotification.Initialize<CrossPushNotificationListener>("KEY watsoever"); //CrossPushNotification.Current.Register(); // get screen width and height //Point size = new Point(); Android.Util.DisplayMetrics size = new Android.Util.DisplayMetrics(); WindowManager.DefaultDisplay.GetMetrics(size); App.ScreenWidth = size.WidthPixels / Resources.DisplayMetrics.Density; App.ScreenHeight = size.HeightPixels / Resources.DisplayMetrics.Density; Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity = this; LoadApplication(new App()); }
public void GetScreenMetrics(bool setDisplaySize) { Android.Util.DisplayMetrics metrics = new Android.Util.DisplayMetrics(); WindowManager.DefaultDisplay.GetMetrics(metrics); screenWidth = metrics.WidthPixels; screenHeight = metrics.HeightPixels; pixelDensity = metrics.Density; float xPxPerIn = metrics.Xdpi; float xDpPerIn = metrics.Xdpi / pixelDensity; dpWidth = screenWidth / pixelDensity; if (setDisplaySize) { if (dpWidth >= 360) { Settings.DisplaySize = 1; } else { Settings.DisplaySize = 0; } } c.Log("ScreenWidth " + screenWidth + " ScreenHeight " + screenHeight + " PixelDensity " + pixelDensity + " XPxPerIn " + xPxPerIn + " XDpPerIn " + xDpPerIn + " DpWidth " + dpWidth); }
private void JSInterface_OnShowBrowser(object sender, int e) { RunOnUiThread(() => { int dp = 0; Log.LogMsg("Trying to show browser.. checking position"); try { Android.Util.DisplayMetrics metrics = new Android.Util.DisplayMetrics(); WindowManager.DefaultDisplay.GetMetrics(metrics); float density = metrics.Density; Log.LogMsg($"density is {density}"); dp = (int)Math.Ceiling(e * density); } catch (Exception ex) { Log.LogErr("couldn't get dp"); return; } try { _webView.LayoutParameters = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MatchParent, dp); _isBrowserShown = true; } catch (Exception ex) { Log.LogErr("coudln't set _webView layout", ex); return; } Log.LogMsg($"Putting browser at {dp}"); }); }
private int DpToPixels(float valueInDp) { Android.Util.DisplayMetrics metrics = _contex.Resources.DisplayMetrics; var pixels = Android.Util.TypedValue.ApplyDimension(Android.Util.ComplexUnitType.Dip, valueInDp, metrics); return(Convert.ToInt32(System.Math.Round(pixels))); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.FeedingTimeScheme); HorizontalScrollView animalScroller; HorizontalScrollView timelineScroller; Android.Util.DisplayMetrics metrics = Resources.DisplayMetrics; feedingtimeLineHeight = (int)(metrics.HeightPixels / 8.5); ImageView banner = FindViewById <ImageView>(Resource.Id.homeBanner); banner.Click += delegate { StartActivity(typeof(MainActivity)); }; SetTimeline(); animalScroller = FindViewById <HorizontalScrollView>(Resource.Id.animalScroller); timelineScroller = FindViewById <HorizontalScrollView>(Resource.Id.timelineScrollView); SetFeedingtimeBlocks(); ScrollViewSyncer(animalScroller, timelineScroller); }
static ViewHelper() { using (Android.Util.DisplayMetrics displayMetrics = Android.App.Application.Context.Resources.DisplayMetrics) { // WARNING: The Density value is not completely based on the DPI of the device. // On two 8" devices, the Density may not be consistent. _cachedDensity = displayMetrics.Density; if (FeatureConfiguration.Font.IgnoreTextScaleFactor) { // To disable text scaling, we put the Density value in ScaledDensity so that the ratio between them is 1. // This ensures it's disabled for everything using ScaledDensity (e.g. TextBlock, TextBox, AppBarButton, etc.) // https://developer.xamarin.com/api/property/Android.Util.DisplayMetrics.ScaledDensity/ displayMetrics.ScaledDensity = displayMetrics.Density; } _cachedScaledDensity = displayMetrics.ScaledDensity; _cachedScaledXDpi = displayMetrics.Xdpi; } if (typeof(ViewHelper).Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) { typeof(ViewHelper).Log().DebugFormat("Display Scale is {0}", Scale); } Architecture = Java.Lang.JavaSystem.GetProperty("os.arch"); }
/// <summary> /// /// </summary> private void SetIndicatorPosition() { Android.Util.DisplayMetrics dm = Context.ApplicationContext.Resources.DisplayMetrics; this.Measure(MeasureSpec.MakeMeasureSpec(dm.WidthPixels, MeasureSpecMode.Exactly), MeasureSpec.MakeMeasureSpec(dm.HeightPixels, MeasureSpecMode.Exactly)); SetProgressViewOffset(false, (this.GetChildAt(0).MeasuredHeight * -1), 4); }
private DisplayInformation() { #if __ANDROID__ _metrics = Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity.Resources.DisplayMetrics; #elif __IOS__ || __TVOS__ _screen = UIApplication.SharedApplication.KeyWindow.Screen; #endif }
public double getWidth() { Display d = windowManager.DefaultDisplay; Android.Util.DisplayMetrics m = new Android.Util.DisplayMetrics(); d.GetMetrics(m); return((int)((m.WidthPixels) / m.Density)); }
public virtual View Render(Activity activity, ToastNotificationType type, string title, string description, object context) { var view = activity.LayoutInflater.Inflate(Resource.Layout.crouton, null); var titleTv = view.FindViewById <TextView>(Resource.Id.title); var descTv = view.FindViewById <TextView>(Resource.Id.desc); var image = view.FindViewById <ImageView>(Resource.Id.image); titleTv.Text = title; descTv.Text = description; switch (type) { case ToastNotificationType.Info: image.SetImageResource(Resource.Drawable.info); view.SetBackgroundColor(new Color(42, 112, 153)); break; case ToastNotificationType.Success: image.SetImageResource(Resource.Drawable.success); view.SetBackgroundColor(new Color(69, 145, 34)); break; case ToastNotificationType.Warning: image.SetImageResource(Resource.Drawable.warning); view.SetBackgroundColor(new Color(180, 125, 1)); break; case ToastNotificationType.Error: image.SetImageResource(Resource.Drawable.error); view.SetBackgroundColor(new Color(206, 24, 24)); break; case ToastNotificationType.Custom: _imageSetterForCustomType(context, image); view.SetBackgroundColor(_backgroundColorForCustomTypeResolver(context)); break; default: throw new ArgumentOutOfRangeException("type"); } // First, we get application metrics IWindowManager windowManager = Application.Context.GetSystemService(Context.WindowService).JavaCast <IWindowManager>(); var metrics = new Android.Util.DisplayMetrics(); windowManager.DefaultDisplay.GetMetrics(metrics); // then we convert statusbar height in dpi to real pixels int statusBarDpiHeight = 24; int sizeInPixels = Convert.ToInt32(Math.Ceiling(statusBarDpiHeight * metrics.Density)); // and least we set the Y of the view to be just under the statusbar view.SetY(sizeInPixels); return(view); }
public static float convertDpToPixel(float dp, Context context) { Resources resources = context.Resources; Android.Util.DisplayMetrics metrics = resources.DisplayMetrics; float px = dp * metrics.Density; return(px); }
private static void AdjustScaledDensity(Android.Util.DisplayMetrics displayMetrics) { if (FeatureConfiguration.Font.IgnoreTextScaleFactor) { // To disable text scaling, we put the Density value in ScaledDensity so that the ratio between them is 1. // This ensures it's disabled for everything using ScaledDensity (e.g. TextBlock, TextBox, AppBarButton, etc.) // https://developer.xamarin.com/api/property/Android.Util.DisplayMetrics.ScaledDensity/ displayMetrics.ScaledDensity = displayMetrics.Density; } }
protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new MobileApp.App()); Android.Util.DisplayMetrics v = Resources.DisplayMetrics; App.Height = v.HeightPixels; App.Width = v.WidthPixels; }
// инициализация класса "игра" public PacManGame() { // инициализация графики Graphics = new GraphicsDeviceManager(this); var metric = new Android.Util.DisplayMetrics(); Activity.WindowManager.DefaultDisplay.GetMetrics(metric); // установка параметров экрана Graphics.IsFullScreen = true; Graphics.PreferredBackBufferWidth = metric.WidthPixels; Graphics.PreferredBackBufferHeight = metric.HeightPixels; CurrentWidth = Graphics.PreferredBackBufferWidth; CurrentHeigth = Graphics.PreferredBackBufferHeight; Graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight; UpdateScreenAttributies(); string strlocale = Locale.Default.ToString(); strlocale = strlocale.Substring(0, 2); if (strlocale.Equals("ru") || strlocale.Equals("be") || strlocale.Equals("uk") || strlocale.Equals("sr") || strlocale.Equals("kz")) { Language = "ru"; strScore = "Счет: "; strRecord = "Рекорд: "; strScoreAmount = "Число очков: "; strRecordString = "Рекорд "; strRecordNotReached = " не был побит."; strPacmanInjured = "Pacman был ранен о границы поля..."; strNewRecord = "Поставлен рекорд "; } else { Language = "en"; strScore = "Score: "; strRecord = "Record: "; strScoreAmount = "Reached score: "; strRecordString = "Record "; strRecordNotReached = " was not reached."; strPacmanInjured = "Pacman was injured by field border..."; strNewRecord = "New record reached: "; } var locale = new Locale(Language); // languageIso is locale string Locale.Default = locale; var config = new Android.Content.Res.Configuration { Locale = locale }; Activity.Resources.UpdateConfiguration(config, Activity.Resources.DisplayMetrics); }
public AndroidDevice() { Android.Util.DisplayMetrics dm = new Android.Util.DisplayMetrics(); var context = (Activity)Forms.Context; ((Activity)context).WindowManager.DefaultDisplay.GetMetrics(dm); var density = dm.Density; ScreenWidth = (int)(dm.WidthPixels / density); ScreenHeight = (int)(dm.HeightPixels / density); }
void SetMarkers(float zoomLevel) { double minLatitude = mMap.Projection.VisibleRegion.NearLeft.Latitude; double maxLatitude = mMap.Projection.VisibleRegion.FarLeft.Latitude; double minLongtitude = mMap.Projection.VisibleRegion.NearLeft.Longitude; double maxLongtitude = mMap.Projection.VisibleRegion.NearRight.Longitude; mMap.Clear(); Console.WriteLine(mMap.Projection.VisibleRegion); foreach (Attraction attraction in AttractionDataBase.Attractions) { if (attraction.Location.Longitude > minLatitude && attraction.Location.Longitude < maxLatitude && attraction.Location.Latitude > minLongtitude && attraction.Location.Latitude < maxLongtitude) { if (attractionsEnabled.Find(x => x.type == attraction.attractiontype).enabled == true) { System.IO.Stream ims = Assets.Open("img/" + "MissingImage.png"); if (attraction is Animal) { ims = Assets.Open("img/" + "AnimalButtons/" + (attraction as Animal).ImageName + "Button.png"); } else if (attraction is Attraction) { ims = Assets.Open("img/FacilityButtons/" + (attraction as Facility).attractiontype + "/" + attraction.ImageName + "Button.png"); } // load image as Drawable Bitmap bitmap = BitmapFactory.DecodeStream(ims); ims.Close(); Android.Util.DisplayMetrics metrics = Resources.DisplayMetrics; int scaling = ((int)zoomLevel - 11); scaling = (int)Math.Pow(scaling, 3); scaling /= 2; Bitmap scaledBitmap = Bitmap.CreateScaledBitmap(bitmap, scaling, scaling, true); bitmap.Recycle(); //Console.WriteLine("Making marker for: " + attraction.Name); mMap.AddMarker(new MarkerOptions() .SetPosition(new LatLng(attraction.Location.Longitude, attraction.Location.Latitude)) .SetTitle(attraction.Name) .SetIcon(BitmapDescriptorFactory.FromBitmap(scaledBitmap))); } } } }
public virtual View Render(Activity activity, ToastNotificationType type, string title, string description, object context) { var view = activity.LayoutInflater.Inflate(Resource.Layout.crouton, null); var titleTv = view.FindViewById<TextView>(Resource.Id.title); var descTv = view.FindViewById<TextView>(Resource.Id.desc); var image = view.FindViewById<ImageView>(Resource.Id.image); titleTv.Text = title; descTv.Text = description; switch (type) { case ToastNotificationType.Info: image.SetImageResource(Resource.Drawable.info); view.SetBackgroundColor(new Color(42, 112, 153)); break; case ToastNotificationType.Success: image.SetImageResource(Resource.Drawable.success); view.SetBackgroundColor(new Color(69, 145, 34)); break; case ToastNotificationType.Warning: image.SetImageResource(Resource.Drawable.warning); view.SetBackgroundColor(new Color(180, 125, 1)); break; case ToastNotificationType.Error: image.SetImageResource(Resource.Drawable.error); view.SetBackgroundColor(new Color(206, 24, 24)); break; case ToastNotificationType.Custom: _imageSetterForCustomType(context, image); view.SetBackgroundColor(_backgroundColorForCustomTypeResolver(context)); break; default: throw new ArgumentOutOfRangeException("type"); } // First, we get application metrics IWindowManager windowManager = Application.Context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>(); var metrics = new Android.Util.DisplayMetrics(); windowManager.DefaultDisplay.GetMetrics(metrics); // then we convert statusbar height in dpi to real pixels int statusBarDpiHeight = 24; int sizeInPixels = Convert.ToInt32(Math.Ceiling(statusBarDpiHeight * metrics.Density)); // and least we set the Y of the view to be just under the statusbar view.SetY(sizeInPixels); return view; }
/// <summary> /// 开始屏幕录制 /// </summary> public void StartRecord_ActualMethod(Android.App.Result resultCode, Android.Content.Intent data) { string msg = string.Empty; if (resultCode != Android.App.Result.Ok) // 用户拒绝授权 { s_IsRunning.Set(false); msg = "用户已拒绝授权,录制屏幕停止执行。"; System.Diagnostics.Debug.WriteLine(msg); showToast(msg); return; } // System.Threading.Thread.Sleep(500); // 以防截取到授权窗口,停顿 500 ms System.Threading.Thread.Sleep(1000); mProjection = mProjectionManager.GetMediaProjection((int)resultCode, data); // ok = -1 Android.Util.DisplayMetrics displayMetrics = new Android.Util.DisplayMetrics(); mAppActivity.WindowManager.DefaultDisplay.GetRealMetrics(displayMetrics); int width = displayMetrics.WidthPixels; int height = displayMetrics.HeightPixels; initRecorder(width, height); mDisplay = mProjection.CreateVirtualDisplay ( name: "MyAndroidScreenRecord", width: width, height: height, dpi: (int)Android.Util.DisplayMetricsDensity.Medium, // TODO Dpi // DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, // TODO Xamarin.Android 中没有此参数 flags: Android.Views.DisplayFlags.Presentation, surface: mMediaRecorder.Surface, callback: null, handler: null ); msg = "屏幕录像开始"; System.Diagnostics.Debug.WriteLine(msg); // showToast(msg); // 不显示开始信息, 更好地进行录像 //Xamarin.Essentials.MainThread.BeginInvokeOnMainThread(() => //{ mMediaRecorder.Start(); //}); }
private static void PrepareResources(Context context) { if (mMetrics != null) { return; } mMetrics = new Android.Util.DisplayMetrics(); Activity act = (Activity)context; act.WindowManager.DefaultDisplay.GetMetrics(mMetrics); var mgr = context.Assets; mResources = new Android.Content.Res.Resources(mgr, mMetrics, context.Resources.Configuration); }
public override bool OnOptionsItemSelected(IMenuItem item) { if (item == _aboutUsMenu) { Display display = WindowManager.DefaultDisplay; Android.Util.DisplayMetrics metrics = new Android.Util.DisplayMetrics(); display.GetMetrics(metrics); int width = (int)Math.Min(display.Width * 0.8, 360 * metrics.Density); int height = (int)Math.Min(display.Height * 0.8, 480 * metrics.Density); PopupWindow aboutWindow = new PopupWindow(LayoutInflater.Inflate(Resource.Layout.about_us, null, false), width, height); TextView appVersionText = aboutWindow.ContentView.FindViewById <TextView>(Resource.Id.AboutUsVersionTextView); appVersionText.Text = String.Format("{0}: {1}", Resources.GetString(Resource.String.application_version), this.PackageManager.GetPackageInfo(PackageName, Android.Content.PM.PackageInfoFlags.Activities).VersionName); Button closeButton = aboutWindow.ContentView.FindViewById <Button>(Resource.Id.AboutUsCloseButton); closeButton.Click += delegate { aboutWindow.Dismiss(); }; TextView aboutUsNoteTextView = aboutWindow.ContentView.FindViewById <TextView>(Resource.Id.AboutUsModuleInfoTextView); //Emgu.CV.Util.VectorOfOclPlatformInfo oclInfo = Emgu.CV.OclInvoke.GetPlatformInfo(); String txt = String.Format("Has OpenCL: {0}", CvInvoke.HaveOpenCL); if (CvInvoke.HaveOpenCL) { txt = String.Format("{0}{1}Use OpenCL: {2}{3}{4}{5}", txt, System.Environment.NewLine, CvInvoke.UseOpenCL, System.Environment.NewLine, CvInvoke.OclGetPlatformsSummary(), System.Environment.NewLine); } txt = String.Format("{0}{1}Has Cuda: {2}", txt, System.Environment.NewLine, CudaInvoke.HasCuda); aboutUsNoteTextView.Text = txt; aboutWindow.ShowAtLocation(this.Window.DecorView, GravityFlags.Center, 0, 0); } else if (item == _settingsMenu) { Intent settingsIntent = new Intent(this, typeof(SettingActivity)); StartActivity(settingsIntent); } return(base.OnOptionsItemSelected(item)); }
public MainGame() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; var metric = new Android.Util.DisplayMetrics(); Activity.WindowManager.DefaultDisplay.GetMetrics(metric); graphics.IsFullScreen = true; currentScreenSize = metric.WidthPixels < metric.HeightPixels ? new Point(metric.WidthPixels, metric.HeightPixels) : new Point(metric.HeightPixels, metric.WidthPixels); graphics.PreferredBackBufferWidth = currentScreenSize.X; graphics.PreferredBackBufferHeight = currentScreenSize.Y; graphics.SupportedOrientations = DisplayOrientation.Portrait | DisplayOrientation.PortraitDown; }
static ViewHelper() { using (Android.Util.DisplayMetrics displayMetrics = Android.App.Application.Context.Resources.DisplayMetrics) { // WARNING: The Density value is not completely based on the DPI of the device. // On two 8" devices, the Density may not be consistent. _cachedDensity = displayMetrics.Density; _cachedScaledDensity = displayMetrics.ScaledDensity; _cachedScaledXDpi = displayMetrics.Xdpi; } if (typeof(ViewHelper).Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) { typeof(ViewHelper).Log().DebugFormat("Display Scale is {0}", Scale); } Architecture = Java.Lang.JavaSystem.GetProperty("os.arch"); }
public CloudHunt() { graphics = new GraphicsDeviceManager(this); var metric = new Android.Util.DisplayMetrics(); Activity.WindowManager.DefaultDisplay.GetMetrics(metric); Content.RootDirectory = "Content"; graphics.IsFullScreen = true; graphics.PreferredBackBufferWidth = metric.WidthPixels; graphics.PreferredBackBufferHeight = (int)wantedHeight; graphics.SupportedOrientations = DisplayOrientation.PortraitDown; graphics.ApplyChanges(); //Virtual scale virtualScale = graphics.PreferredBackBufferWidth / wantedWidth; }
public override void ApplicationDidFinishLaunching(CCApplication application, CCWindow mainWindow) { application.ContentRootDirectory = "Content"; var windowSize = mainWindow.WindowSizeInPixels; var desiredWidth = 1024.0f; var desiredHeight = 768.0f; // This will set the world bounds to be (0,0, w, h) // CCSceneResolutionPolicy.ShowAll will ensure that the aspect ratio is preserved CCScene.SetDefaultDesignResolution(desiredWidth, desiredHeight, CCSceneResolutionPolicy.ShowAll); // Determine whether to use the high or low def versions of our images // Make sure the default texel to content size ratio is set correctly // Of course you're free to have a finer set of image resolutions e.g (ld, hd, super-hd) if (desiredWidth < windowSize.Width) { application.ContentSearchPaths.Add("hd"); } else { application.ContentSearchPaths.Add("ld"); } CCSprite.DefaultTexelToContentSizeRatio = 1.0f; var scene = new CCScene(mainWindow); var introLayer = new IntroLayer(); mainWindow.DisplayStats = true; #if ANDROID var display = Game.Activity.WindowManager.DefaultDisplay; var metrics = new Android.Util.DisplayMetrics(); display.GetMetrics(metrics); mainWindow.StatsScale = (int)metrics.ScaledDensity; #endif scene.AddChild(introLayer); mainWindow.RunWithScene(scene); }
public override void ApplicationDidFinishLaunching(CCApplication application, CCWindow mainWindow) { application.ContentRootDirectory = "Content"; var windowSize = mainWindow.WindowSizeInPixels; var desiredWidth = 1024.0f; var desiredHeight = 768.0f; // This will set the world bounds to be (0,0, w, h) // CCSceneResolutionPolicy.ShowAll will ensure that the aspect ratio is preserved CCScene.SetDefaultDesignResolution(desiredWidth, desiredHeight, CCSceneResolutionPolicy.ShowAll); // Determine whether to use the high or low def versions of our images // Make sure the default texel to content size ratio is set correctly // Of course you're free to have a finer set of image resolutions e.g (ld, hd, super-hd) if (desiredWidth < windowSize.Width) { application.ContentSearchPaths.Add("hd"); } else { application.ContentSearchPaths.Add("ld"); } CCSprite.DefaultTexelToContentSizeRatio = 1.0f; var scene = new CCScene(mainWindow); var introLayer = new IntroLayer(); mainWindow.DisplayStats = true; #if ANDROID var display = Game.Activity.WindowManager.DefaultDisplay; var metrics = new Android.Util.DisplayMetrics(); display.GetMetrics(metrics); mainWindow.StatsScale = (int)metrics.ScaledDensity ; #endif scene.AddChild(introLayer); mainWindow.RunWithScene(scene); }
/// <summary> /// The surface is changed. /// </summary> /// <param name="holder">A surface holder.</param> /// <param name="format">A new pixel format of the surface.</param> /// <param name="width">A surface width.</param> /// <param name="height">A surface height.</param> public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height) { int displayWidth; int displayHeight; Activity activity = Context as Activity; // if activity is not empty if (activity != null) { // get display size Android.Util.DisplayMetrics displayMetrics = new Android.Util.DisplayMetrics(); activity.WindowManager.DefaultDisplay.GetMetrics(displayMetrics); displayWidth = displayMetrics.WidthPixels; displayHeight = displayMetrics.HeightPixels; } // if activity is empty else { // get width if (_barcodeScannerOveraly.Width < width) { displayWidth = _barcodeScannerOveraly.Width; } else { displayWidth = width; } // get height if (_barcodeScannerOveraly.Height < height) { displayHeight = _barcodeScannerOveraly.Height; } else { displayHeight = height; } } SurfaceCreated(holder, displayWidth, displayHeight); }
public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; var metric = new Android.Util.DisplayMetrics(); Activity.WindowManager.DefaultDisplay.GetMetrics(metric); // установка параметров экрана graphics.IsFullScreen = true; graphics.PreferredBackBufferWidth = metric.WidthPixels; graphics.PreferredBackBufferHeight = metric.HeightPixels; CurrentWidth = graphics.PreferredBackBufferWidth; CurrentHeigth = graphics.PreferredBackBufferHeight; graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight; UpdateScreenAttributies(); Debug.WriteLine("CurrentWidth: " + CurrentWidth); Debug.WriteLine("CurrentHeigth: " + CurrentHeigth); Debug.WriteLine("NominalWidth: " + NominalWidth); Debug.WriteLine("NominalHeight: " + NominalHeight); Debug.WriteLine("Dx: " + Dx); Debug.WriteLine("Dy: " + Dy); }
public void Screenshot_ActualMethod(Android.App.Result resultCode, Android.Content.Intent data) { string msg = string.Empty; if (resultCode != Android.App.Result.Ok) // 用户拒绝授权 { s_IsRunning.Set(false); msg = "用户已拒绝授权,屏幕截图停止执行。"; System.Diagnostics.Debug.WriteLine(msg); showToast(msg); return; } // System.Threading.Thread.Sleep(500); // 以防截取到授权窗口,停顿 500 ms System.Threading.Thread.Sleep(1000); // 以防截取到授权窗口,停顿 500 ms mProjection = mProjectionManager.GetMediaProjection((int)resultCode, data); // ok = -1 Android.Util.DisplayMetrics displayMetrics = new Android.Util.DisplayMetrics(); mAppActivity.WindowManager.DefaultDisplay.GetRealMetrics(displayMetrics); int width = displayMetrics.WidthPixels; int height = displayMetrics.HeightPixels; if (mImageReader != null) { mImageReader.Close(); mImageReader = null; } if (mDisplay != null) { mDisplay.Release(); mDisplay = null; } mImageReader = Android.Media.ImageReader.NewInstance ( width: width, height: height, // Bitmap.Config.ARGB_8888 // Android 源码传入参数 // format: Android.Graphics.ImageFormatType.FlexRgba8888, // 由于没有 Config.ARGB_8888, 故从 AndroidStudio 中获取 Config.ARGB_8888 枚举的值 ( = 1 ) format: (Android.Graphics.ImageFormatType) 1, // Bitmap.Config.ARGB_8888 maxImages: 2 ); mDisplay = mProjection.CreateVirtualDisplay ( name: "MyAndroidScreenshot", width: width, height: height, dpi: (int)Android.Util.DisplayMetricsDensity.Medium, flags: Android.Views.DisplayFlags.Presentation, surface: mImageReader.Surface, callback: null, handler: null ); var listener = new MyScreenshotListener ( width: width, height: height, imageFileDateTime: mImageFileDateTime, dirName: mDirName ); mImageReader.SetOnImageAvailableListener(listener: listener, handler: getBackgroundHandler()); msg = "屏幕截图开始"; System.Diagnostics.Debug.WriteLine(msg); // showToast(msg); // 不显示开始信息, 更好地进行截图 }
public override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetTheme(PreferenceManager.GetDefaultSharedPreferences(ApplicationContext).GetInt("ThemeStyle", Resource.Style.Theme_Sherlock)); RequestWindowFeature(WindowFeatures.ActionBar); SetSlidingActionBarEnabled(true); // Left menu if (PreferenceManager.GetDefaultSharedPreferences(ApplicationContext).GetBoolean("notesReplace", false)) { leftMenuFragment = new NotesFragmentAdvanced(); rightMenuFragment = new MenuFragmentAdvanced(); } else { leftMenuFragment = new MenuFragmentAdvanced(); rightMenuFragment = new NotesFragmentAdvanced(); } contentFragment = new ReaderFragment(); reader = contentFragment as ReaderFragment; // Setup the left menu SetBehindContentView(Resource.Layout.MenuFrame); SupportFragmentManager.BeginTransaction().Replace(Resource.Id.MenuFrame, leftMenuFragment).Commit(); // Setup the content SetContentView(Resource.Layout.ContentFrame); SupportFragmentManager.BeginTransaction().Replace(Resource.Id.ContentFrame, contentFragment).Commit(); // Setup the right menu SlidingMenu.SetSecondaryMenu(Resource.Layout.MenuFrameSecondary); SupportFragmentManager.BeginTransaction().Replace(Resource.Id.MenuFrameSecondary, rightMenuFragment).Commit(); // Get display dimensions of current oriented screen Display display = WindowManager.DefaultDisplay; Android.Util.DisplayMetrics metrics = new Android.Util.DisplayMetrics(); display.GetMetrics(metrics); int width = (int)(metrics.WidthPixels * .333); // Setup the sliding menu SlidingMenu.Mode = SlidingMenuBinding.Lib.SlidingMenu.LeftRight; //SlidingMenu.SetShadowWidthRes(Resource.Dimension.SlidingMenuShadowWidth); //SlidingMenu.SetShadowDrawable(Resource.Drawable.SlidingMenuShadow); SlidingMenu.SetBehindWidth(width * 2); //SlidingMenu.SetFadeDegree(0.35f); SlidingMenu.TouchModeAbove = SlidingMenuBinding.Lib.SlidingMenu.TouchmodeFullscreen; // Enable this so that we can toggle the menu when clicking the action bar home button in `OnOptionsItemSelected` SupportActionBar.SetDisplayHomeAsUpEnabled(true); if (ThisApp.ReaderKind == ReaderKind.BibleReader) { Console.WriteLine("Chapter " + ThisApp.selectedChapter.ChapterNumber.ToString()); // Number of chapters in the selected book int chapterNum = int.Parse(ThisApp.selectedChapter.ChapterNumber.ToString()); offset = chapterNum; Title = ThisApp.selectedChapter.BookAndChapter; } else if (ThisApp.ReaderKind == ReaderKind.PublicationReader) { Title = ThisApp.selectedPublicationArticle.ArticleTitle; } else if (ThisApp.ReaderKind == ReaderKind.DailyTextReader) { ThisApp.selectedDailyText = ThisApp.GetDailyText(reader.FormatDateTime(DateTime.Now)); Title = ThisApp.selectedDailyText.Date; } else if (ThisApp.ReaderKind == ReaderKind.WOLReader) { Title = "Watchtower Online Library"; } // Add the menu if user preferences loadNav = PreferenceManager.GetDefaultSharedPreferences(ApplicationContext).GetBoolean("topNavController", true); if (loadNav && !ThisApp.ReaderKind.Equals(ReaderKind.WOLReader)) { InitializeActionBarItemList(); Title = ""; } ThisApp.LanguageChanged += ThisApp_LanguageChanged; }
public void SetCameraDisplayOrientation(Activity context) { var degrees = 0; var display = context.WindowManager.DefaultDisplay; var rotation = display.Rotation; var displayMetrics = new Android.Util.DisplayMetrics(); display.GetMetrics(displayMetrics); int width = displayMetrics.WidthPixels; int height = displayMetrics.HeightPixels; if ((rotation == SurfaceOrientation.Rotation0 || rotation == SurfaceOrientation.Rotation180) && height > width || (rotation == SurfaceOrientation.Rotation90 || rotation == SurfaceOrientation.Rotation270) && width > height) { switch (rotation) { case SurfaceOrientation.Rotation0: degrees = 90; break; case SurfaceOrientation.Rotation90: degrees = 0; break; case SurfaceOrientation.Rotation180: degrees = 270; break; case SurfaceOrientation.Rotation270: degrees = 180; break; } } //Natural orientation is landscape or square else { switch (rotation) { case SurfaceOrientation.Rotation0: degrees = 0; break; case SurfaceOrientation.Rotation90: degrees = 270; break; case SurfaceOrientation.Rotation180: degrees = 180; break; case SurfaceOrientation.Rotation270: degrees = 90; break; } } Android.Util.Log.Debug("ZXING", "Changing Camera Orientation to: " + degrees); try { camera.SetDisplayOrientation(degrees); } catch (Exception ex) { Android.Util.Log.Error("ZXING", ex.ToString()); } }
public void SetCameraDisplayOrientation(Activity context) { var degrees = 0; var display = context.WindowManager.DefaultDisplay; var rotation = display.Rotation; var displayMetrics = new Android.Util.DisplayMetrics (); display.GetMetrics (displayMetrics); int width = displayMetrics.WidthPixels; int height = displayMetrics.HeightPixels; if((rotation == SurfaceOrientation.Rotation0 || rotation == SurfaceOrientation.Rotation180) && height > width || (rotation == SurfaceOrientation.Rotation90 || rotation == SurfaceOrientation.Rotation270) && width > height) { switch(rotation) { case SurfaceOrientation.Rotation0: degrees = 90; break; case SurfaceOrientation.Rotation90: degrees = 0; break; case SurfaceOrientation.Rotation180: degrees = 270; break; case SurfaceOrientation.Rotation270: degrees = 180; break; } } //Natural orientation is landscape or square else { switch(rotation) { case SurfaceOrientation.Rotation0: degrees = 0; break; case SurfaceOrientation.Rotation90: degrees = 270; break; case SurfaceOrientation.Rotation180: degrees = 180; break; case SurfaceOrientation.Rotation270: degrees = 90; break; } } Android.Util.Log.Debug ("ZXING", "Changing Camera Orientation to: " + degrees); try { camera.SetDisplayOrientation (degrees); } catch (Exception ex) { Android.Util.Log.Error ("ZXING", ex.ToString ()); } }
private Texture2D TextureTargetBad; // шестеренка #endregion Fields #region Constructors // инициализация класса "игра" public PacManGame() { // инициализация графики Graphics = new GraphicsDeviceManager(this); var metric = new Android.Util.DisplayMetrics(); Activity.WindowManager.DefaultDisplay.GetMetrics(metric); // установка параметров экрана Graphics.IsFullScreen = true; Graphics.PreferredBackBufferWidth = metric.WidthPixels; Graphics.PreferredBackBufferHeight = metric.HeightPixels; CurrentWidth = Graphics.PreferredBackBufferWidth; CurrentHeigth = Graphics.PreferredBackBufferHeight; Graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight; UpdateScreenAttributies(); string strlocale = Locale.Default.ToString(); strlocale = strlocale.Substring(0, 2); if (strlocale.Equals("ru") || strlocale.Equals("be") || strlocale.Equals("uk") || strlocale.Equals("sr") || strlocale.Equals("kz")) { Language = "ru"; strScore = "Счет: "; strRecord = "Рекорд: "; strScoreAmount = "Число очков: "; strRecordString = "Рекорд "; strRecordNotReached = " не был побит."; strPacmanInjured = "Pacman был ранен о границы поля..."; strNewRecord = "Поставлен рекорд "; } else { Language = "en"; strScore = "Score: "; strRecord = "Record: "; strScoreAmount = "Reached score: "; strRecordString = "Record "; strRecordNotReached = " was not reached."; strPacmanInjured = "Pacman was injured by field border..."; strNewRecord = "New record reached: "; } var locale = new Locale(Language); // languageIso is locale string Locale.Default = locale; var config = new Android.Content.Res.Configuration {Locale = locale}; Activity.Resources.UpdateConfiguration(config, Activity.Resources.DisplayMetrics); }
private static void PrepareResources(Context context) { if (mMetrics != null) return; mMetrics = new Android.Util.DisplayMetrics(); Activity act = (Activity)context; act.WindowManager.DefaultDisplay.GetMetrics(mMetrics); var mgr = context.Assets; mResources = new Android.Content.Res.Resources(mgr, mMetrics, context.Resources.Configuration); }
private DisplayInformation() { #if __ANDROID__ _metrics = Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity.Resources.DisplayMetrics; #endif }
public override bool OnOptionsItemSelected(IMenuItem item) { if (item == _aboutUsMenu) { Display display = WindowManager.DefaultDisplay; Android.Util.DisplayMetrics metrics = new Android.Util.DisplayMetrics(); display.GetMetrics(metrics); int width = (int)Math.Min(display.Width * 0.8, 360 * metrics.Density); int height = (int)Math.Min(display.Height * 0.8, 480 * metrics.Density); PopupWindow aboutWindow = new PopupWindow(LayoutInflater.Inflate(Resource.Layout.about_us, null, false), width, height); TextView appVersionText = aboutWindow.ContentView.FindViewById<TextView>(Resource.Id.AboutUsVersionTextView); appVersionText.Text = String.Format("{0}: {1}", Resources.GetString(Resource.String.application_version), this.PackageManager.GetPackageInfo(PackageName, Android.Content.PM.PackageInfoFlags.Activities).VersionName); Button closeButton = aboutWindow.ContentView.FindViewById<Button>(Resource.Id.AboutUsCloseButton); closeButton.Click += delegate { aboutWindow.Dismiss(); }; TextView aboutUsNoteTextView = aboutWindow.ContentView.FindViewById<TextView>(Resource.Id.AboutUsModuleInfoTextView); //Emgu.CV.Util.VectorOfOclPlatformInfo oclInfo = Emgu.CV.OclInvoke.GetPlatformInfo(); String txt = String.Format("Has OpenCL: {0}", CvInvoke.HaveOpenCL); if (CvInvoke.HaveOpenCL) { txt = String.Format("{0}{1}Use OpenCL: {2}{3}{4}{5}", txt, System.Environment.NewLine, CvInvoke.UseOpenCL, System.Environment.NewLine, CvInvoke.OclGetPlatformsSummary(), System.Environment.NewLine); } txt = String.Format("{0}{1}Has Cuda: {2}", txt, System.Environment.NewLine, CudaInvoke.HasCuda); aboutUsNoteTextView.Text = txt; aboutWindow.ShowAtLocation(this.Window.DecorView, GravityFlags.Center, 0, 0); } else if (item == _settingsMenu) { Intent settingsIntent = new Intent(this, typeof(SettingActivity)); StartActivity(settingsIntent); } return base.OnOptionsItemSelected(item); }
int getCameraDisplayOrientation(Activity context) { var degrees = 0; var display = context.WindowManager.DefaultDisplay; var rotation = display.Rotation; var displayMetrics = new Android.Util.DisplayMetrics(); display.GetMetrics(displayMetrics); int width = displayMetrics.WidthPixels; int height = displayMetrics.HeightPixels; if ((rotation == SurfaceOrientation.Rotation0 || rotation == SurfaceOrientation.Rotation180) && height > width || (rotation == SurfaceOrientation.Rotation90 || rotation == SurfaceOrientation.Rotation270) && width > height) { switch (rotation) { case SurfaceOrientation.Rotation0: degrees = 90; break; case SurfaceOrientation.Rotation90: degrees = 0; break; case SurfaceOrientation.Rotation180: degrees = 270; break; case SurfaceOrientation.Rotation270: degrees = 180; break; } } //Natural orientation is landscape or square else { switch (rotation) { case SurfaceOrientation.Rotation0: degrees = 0; break; case SurfaceOrientation.Rotation90: degrees = 270; break; case SurfaceOrientation.Rotation180: degrees = 180; break; case SurfaceOrientation.Rotation270: degrees = 90; break; } } return(degrees); }
//int cameraDegrees = 0; int getCameraDisplayOrientation(Activity context) { var degrees = 0; var display = context.WindowManager.DefaultDisplay; var rotation = display.Rotation; var displayMetrics = new Android.Util.DisplayMetrics (); display.GetMetrics (displayMetrics); int width = displayMetrics.WidthPixels; int height = displayMetrics.HeightPixels; if((rotation == SurfaceOrientation.Rotation0 || rotation == SurfaceOrientation.Rotation180) && height > width || (rotation == SurfaceOrientation.Rotation90 || rotation == SurfaceOrientation.Rotation270) && width > height) { switch(rotation) { case SurfaceOrientation.Rotation0: degrees = 90; break; case SurfaceOrientation.Rotation90: degrees = 0; break; case SurfaceOrientation.Rotation180: degrees = 270; break; case SurfaceOrientation.Rotation270: degrees = 180; break; } } //Natural orientation is landscape or square else { switch(rotation) { case SurfaceOrientation.Rotation0: degrees = 0; break; case SurfaceOrientation.Rotation90: degrees = 270; break; case SurfaceOrientation.Rotation180: degrees = 180; break; case SurfaceOrientation.Rotation270: degrees = 90; break; } } return degrees; }
public override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetTheme(PreferenceManager.GetDefaultSharedPreferences(ApplicationContext).GetInt("ThemeStyle", Resource.Style.Theme_Sherlock)); RequestWindowFeature(WindowFeatures.ActionBar); SetSlidingActionBarEnabled(true); // Left menu if (PreferenceManager.GetDefaultSharedPreferences(ApplicationContext).GetBoolean("notesReplace", false)) { leftMenuFragment = new NotesFragment(); rightMenuFragment = new MenuFragmentAdvanced(); } else { leftMenuFragment = new MenuFragmentAdvanced(); rightMenuFragment = new NotesFragment(); } SetContentView(Resource.Layout.ViewPagerLayout); // Setup the left menu SetBehindContentView(Resource.Layout.MenuFrame); SupportFragmentManager.BeginTransaction().Replace(Resource.Id.MenuFrame, leftMenuFragment).Commit(); // Setup the right menu SlidingMenu.SetSecondaryMenu(Resource.Layout.MenuFrameSecondary); SupportFragmentManager.BeginTransaction().Replace(Resource.Id.MenuFrameSecondary, rightMenuFragment).Commit(); // Get display dimensions of current oriented screen Display display = WindowManager.DefaultDisplay; Android.Util.DisplayMetrics metrics = new Android.Util.DisplayMetrics(); display.GetMetrics(metrics); int width = (int)(metrics.WidthPixels * .333); // Setup the sliding menu SlidingMenu.Mode = SlidingMenuBinding.Lib.SlidingMenu.LeftRight; SlidingMenu.SetShadowWidthRes(Resource.Dimension.SlidingMenuShadowWidth); SlidingMenu.SetShadowDrawable(Resource.Drawable.SlidingMenuShadow); SlidingMenu.SetBehindWidth(width * 2); SlidingMenu.SetFadeDegree(0.35f); SlidingMenu.TouchModeAbove = SlidingMenuBinding.Lib.SlidingMenu.TouchmodeMargin; // Enable this so that we can toggle the menu when clicking the action bar home button in `OnOptionsItemSelected` SupportActionBar.SetDisplayHomeAsUpEnabled(true); InitializeView(); ThisApp.LanguageChanged += ThisApp_LanguageChanged; }