public static BitmapFactory.Options GetBitmapOptionsOfImage(Android.Content.Res.Resources res, string imageName) { BitmapFactory.Options options = new BitmapFactory.Options { InJustDecodeBounds = true }; //use reflection to get the resource id from resources int resourceId = (int)typeof(Resource.Drawable).GetField(imageName).GetValue(null); // The result will be null because InJustDecodeBounds == true. Bitmap result = BitmapFactory.DecodeResource(res, resourceId, options); return(options); }
private void PrepareResources() { if (_isPrepared) { return; } _isPrepared = true; var context = AndroidDevice.Instance.Context; _packageName = context.PackageName; var metrics = new DisplayMetrics(); context.WindowManager.DefaultDisplay.GetMetrics(metrics); _resources = new Android.Content.Res.Resources(context.Assets, metrics, context.Resources.Configuration); }
private T GetResource <T>(Func <Android.Content.Res.Resources, T> operation, CultureInfo culture = null) { Reset(); if (culture == null || CultureInfo.CurrentUICulture.Equals(culture)) { return(operation(AndroidDevice.Instance.Context.Resources)); } Configuration conf = AndroidDevice.Instance.Context.Resources.Configuration; conf.Locale = new Locale(culture.TwoLetterISOLanguageName); var metrics = new DisplayMetrics(); AndroidDevice.Instance.Context.WindowManager.DefaultDisplay.GetMetrics(metrics); var resources = new Android.Content.Res.Resources(AndroidDevice.Instance.Context.Assets, metrics, conf); conf.Locale = new Locale(CultureInfo.CurrentUICulture.TwoLetterISOLanguageName); var retVal = operation(resources); resources = new Android.Content.Res.Resources(AndroidDevice.Instance.Context.Assets, metrics, conf); return(retVal); }
public override View GetView(int position, View convertView, ViewGroup parent) { var item = machines[position]; // Remove the file extention from the image filename Android.Content.Res.Resources res = context.Resources; BitmapFactory.Options options = ImageHelper.GetBitmapOptionsOfImage(res, item.PictureUrl); // Converting Drawable Resource to Bitmap Bitmap bitmapToDisplay = ImageHelper.LoadScaledDownBitmapForDisplay(res, options, 150, 150, item.PictureUrl); if (convertView == null) { if (this.context.GetType() == typeof(BuildRoutine) || this.context.GetType() == typeof(selectMachines)) { convertView = context.LayoutInflater.Inflate(Resource.Layout.MachinewithCheck, null); convertView.FindViewById <TextView>(Resource.Id.MachineName1).Text = item.Name; convertView.FindViewById <TextView>(Resource.Id.shortDescription1).Text = item.shortDesc; // convertView.FindViewById<ImageView>(Android.Resource.Id.Icon).; convertView.FindViewById <ImageView>(Resource.Id.machineIcon1).SetImageBitmap(bitmapToDisplay); CheckBox check = convertView.FindViewById <CheckBox>(Resource.Id.selectMachineCheck); check.SetTag(Resource.Id.selectMachineCheck, item.Name); check.Click += AllMachinesAdapter_Click; } else { convertView = context.LayoutInflater.Inflate(Resource.Layout.MachineListRow, null); convertView.FindViewById <TextView>(Resource.Id.MachineName).Text = item.Name; convertView.FindViewById <TextView>(Resource.Id.shortDescription).Text = item.shortDesc; // convertView.FindViewById<ImageView>(Android.Resource.Id.Icon).; convertView.FindViewById <ImageView>(Resource.Id.machineIcon).SetImageBitmap(bitmapToDisplay); } } return(convertView); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); context = Application.Context; #region Мова ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(context); ISharedPreferencesEditor editor = prefs.Edit(); languagesId = prefs.GetInt("key_languageId", 1); if (languagesId == 1) { LanguageCodevalue = "en"; } else if (languagesId == 2) { LanguageCodevalue = "fr"; } else if (languagesId == 3) { LanguageCodevalue = "de"; } else if (languagesId == 4) { LanguageCodevalue = "it"; } else if (languagesId == 5) { LanguageCodevalue = "es"; } else if (languagesId == 6) { LanguageCodevalue = "pt"; } else if (languagesId == 7) { LanguageCodevalue = "cs"; } else if (languagesId == 8) { LanguageCodevalue = "pl"; } else if (languagesId == 9) { LanguageCodevalue = "ru"; } else if (languagesId == 10) { LanguageCodevalue = "uk"; } else if (languagesId == 11) { LanguageCodevalue = "ja"; } else if (languagesId == 12) { LanguageCodevalue = "ko"; } Android.Content.Res.Resources res = this.Resources; DisplayMetrics Dm = res.DisplayMetrics; Android.Content.Res.Configuration conf = res.Configuration; if (LanguageCodevalue != null) { conf.SetLocale(new Locale(LanguageCodevalue)); } else { conf.SetLocale(new Locale("en")); } res.UpdateConfiguration(conf, Dm); #endregion Window.AddFlags(WindowManagerFlags.Fullscreen); SetContentView(Resource.Layout._splashScreenNew); gifImageView = FindViewById <GifImageView>(Resource.Id.gifSplashScreen); var assets1 = Assets.List(string.Empty); if (assets1.Any()) { var videoFilename = assets1.FirstOrDefault(a => a.EndsWith(".gif")); if (!string.IsNullOrWhiteSpace(videoFilename)) { var fileDescriptor = Assets.OpenFd(videoFilename); using (var input = this.Assets.Open(videoFilename, Access.Streaming)) { byte[] buffer; using (Stream s = input) { long length = fileDescriptor.Length; buffer = new byte[length]; s.Read(buffer, 0, (int)length); gifImageView.SetBytes(buffer); gifImageView.StartAnimation(); } } } } System.Timers.Timer timer = new System.Timers.Timer(); timer.Interval = 1400; timer.AutoReset = false; timer.Elapsed += Timer_Elapsed; timer.Start(); }
/// <summary> /// Asynchronously loads a composition from a raw json object. This is useful for animations loaded from the network. /// </summary> public static LottieComposition.ICancellable FromJson(Android.Content.Res.Resources res, JSONObject json, Action <LottieComposition> onLoaded) { return(LottieComposition.FromJson(res, json, new ActionCompositionLoaded(onLoaded))); }
//Внутренний метод для получения фото private List <Android.Graphics.Bitmap> GetEventsPhotosInternal(EventShort[] NewEvents) //it was Photo[] { List <Android.Graphics.Bitmap> newPhotos = new List <Android.Graphics.Bitmap>(); if (CheckServerDataPresent(true)) //Если данные от сервера есть { //TO DO //using (var client = new UserClientExchange()) //{ // var syncSessionId = client.Login("Emeri", "Emeri", new Captcha()); // Photo[] serverPhotos = new Photo[NewEvents.Length]; // //Цикл по всем событиям // for (int i = 0; i < NewEvents.Length; i += 1) // { // //Обработка информации о фотках // if (NewEvents[i].PrimaryPhotoId.HasValue) //Если у события есть фото NewEvents[i]. || // { // try // { // for (int howManyTimesTryDownload = 0; howManyTimesTryDownload < 3; howManyTimesTryDownload++) // { // //Проверяем, нет ли у нас уже фото // string filename = "EventMainPhoto_" + NewEvents[i].PrimaryPhotoId; // if (!File.Exists(Path.Combine(WorkingInetAndSQL.destinationPath, filename))) //Если фото нет на диске, то загружаем очередное фото и помещаем в List // { // serverPhotos[i] = client.GetPhoto(syncSessionId, NewEvents[i].PrimaryPhotoId.Value, true); // //Добавляем Bitmap в List // Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeByteArray(serverPhotos[i].Data, 0, serverPhotos[i].Data.Length); // newPhotos.Add(bmp); // //Сохраняем фотку на диск // using (var stream = new BufferedStream(File.OpenWrite(Path.Combine(WorkingInetAndSQL.destinationPath, filename)))) // bmp.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, stream); // } // else //Если же они уже есть на диске, просто берем с диска // { // Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeFile(Path.Combine(WorkingInetAndSQL.destinationPath, filename)); // newPhotos.Add(bmp); // } // howManyTimesTryDownload = 3; // } // } // catch (Exception e) // { // var k = e.Message; // //И пробуем работать без Интернета! // } // } // else //Если фото нет, используем стандартное фото категории // { // var options = new Android.Graphics.BitmapFactory.Options // { // InJustDecodeBounds = false, // }; // Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeResource(res, Resource.Drawable.Leo, options); // newPhotos.Add(bmp); // } // } // client.Logout(syncSessionId); //} } else //Если данных от сервера нет { //Цикл по всем событиям for (int i = 0; i < NewEvents.Length; i += 1) { //Обработка информации о фотках if (NewEvents[i].PrimaryPhotoId.HasValue) //Если у события есть фото { string filename = "EventMainPhoto_" + NewEvents[i].PrimaryPhotoId; if (File.Exists(Path.Combine(WorkingInetAndSQL.destinationPath, filename))) //Если они уже есть на диске, просто берем с диска { Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeFile(Path.Combine(WorkingInetAndSQL.destinationPath, filename)); newPhotos.Add(bmp); } else //Если у события вообще есть фото, но на диске нет { var options = new Android.Graphics.BitmapFactory.Options { InJustDecodeBounds = false, }; Context context = Android.App.Application.Context; Android.Content.Res.Resources res = context.Resources; Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeResource(res, Resource.Drawable.Leo, options); newPhotos.Add(bmp); } } else //Если у события фото нет { var options = new Android.Graphics.BitmapFactory.Options { InJustDecodeBounds = false, }; Context context = Android.App.Application.Context; Android.Content.Res.Resources res = context.Resources; Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeResource(res, Resource.Drawable.Leo, options); newPhotos.Add(bmp); } } } return(newPhotos); }
public static Bitmap GetDrawable(Android.Content.Res.Resources res, int id) { return(BitmapFactory.DecodeStream(res.OpenRawResource(id))); }
//Crea Botones de la botonera principal public List <LinearLayout> CrearBotonera(List <LinearLayout> layouts, List <Boton> botones, int startLayoutIndex, int endLayoutIndex, Android.Content.Res.Resources resources) { int layoutIndex = 0; int buttonsIndex = 0; List <LinearLayout> principalButtonsToAssignAction = new List <LinearLayout>(); foreach (LinearLayout layout in layouts) { if (layoutIndex >= startLayoutIndex && layoutIndex < endLayoutIndex && buttonsIndex < botones.Count) { Boton button = botones[buttonsIndex]; String botonTitle = (button.getLabel().Length > 0) ? button.getLabel() : button.getFuncion(); if (botonTitle.Length > 0) { LinearLayout.LayoutParams myParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent, 1); layout.RemoveAllViews(); myParams.SetMargins(0, 3, 3, 0); layout.WeightSum = 2; layout.Orientation = Android.Widget.Orientation.Vertical; layout.LayoutParameters = myParams; ImageView buttonImage = new ImageView(Application.Context); if (button.getImagen().Length > 0) { LinearLayout.LayoutParams imageViewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent, 1); imageViewParams.SetMargins(0, 5, 0, 0); buttonImage.LayoutParameters = imageViewParams; String mDrawableName = button.getImagen(); //Se necesita saber si el nombre de la imagen es un codigo, para así agregar 'p' al String de la imagen y poder obtenerla //por ejemplo, un código de la imagen puede ser 0911900, y su nombre será p0911900.png, si la imagen posee solo numeros //cumplirá con la ER y se le agregará una p al principio para poder leerla String reg = "\\d.*\\d"; Regex r = new Regex(reg, RegexOptions.IgnoreCase); Match m = r.Match(mDrawableName); if (m.Success) { mDrawableName = "p" + button.getImagen(); } //LOS BOTONES DE LAS CATEGORIAS TIENEN UN NOMBRE EN EL XML QUE NO SE PUEDE LEER EN ANDROID, SE LLAMA LA FUNCIÓN PARA CAMBIARLO if (button.getCategorias().Equals("Categorias") && button.getLabel() != null) { mDrawableName = capitalCaseTo_snake_case(button.getImagen()); } int resID = resources.GetIdentifier(mDrawableName, "drawable", Application.Context.PackageName); buttonImage.SetImageResource(resID); layout.AddView(buttonImage); } TextView buttonTitle = new TextView(Application.Context); LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent, 1); buttonTitle.LayoutParameters = textViewParams; buttonTitle.Gravity = GravityFlags.Center; layout.AddView(buttonTitle); button.SetButtonLayout(layout); layout.SetTag(Resource.Id.TAG_ONLINE_ID, button.getLabel() + "," + button.getFuncion() + "," + button.getCategorias()); principalButtonsToAssignAction.Add(layout); buttonTitle.Text = botonTitle; //SetOnPressedStyleToButton(layout, button.getLabel()); } buttonsIndex++; } layoutIndex++; } return(principalButtonsToAssignAction); }