private void applyRenderers() { if (renderers != null) { Spannable spannableString = new SpannableString(view.getText()); Set<String> spanPatterns = renderers.keySet(); for (String spanPattern : spanPatterns) { Pattern pattern = Pattern.compile(spanPattern); Matcher matcher = pattern.matcher(spannableString); while (matcher.find()) { int end = matcher.end(); int start = matcher.start(); ViewSpanRenderer renderer = renderers.get(spanPattern); String text = matcher.group(0); View view = renderer.getView(text, context); BitmapDrawable bitmpaDrawable = (BitmapDrawable) ViewUtils.convertViewToDrawable(view); bitmpaDrawable.setBounds( UPPER_LEFT_X, UPPER_LEFT_Y, bitmpaDrawable.getIntrinsicWidth(), bitmpaDrawable.getIntrinsicHeight()); spannableString.setSpan( new ImageSpan(bitmpaDrawable), start, end, DEFAULT_RENDER_APPLY_MODE); if (renderer instanceof ViewSpanClickListener) { enableClickEvents(); ClickableSpan clickableSpan = getClickableSpan(text, (ViewSpanClickListener) renderer); spannableString.setSpan(clickableSpan, start, end, DEFAULT_RENDER_APPLY_MODE); } } } view.setText(spannableString); } }
public DessertCaseView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); final Resources res = getResources(); mStarted = false; mCellSize = res.getDimensionPixelSize(R.dimen.dessert_case_cell_size); final BitmapFactory.Options opts = new BitmapFactory.Options(); if (mCellSize < 512) { // assuming 512x512 images opts.inSampleSize = 2; } opts.inMutable = true; Bitmap loaded = null; for (int[] list : new int[][] {PASTRIES, RARE_PASTRIES, XRARE_PASTRIES, XXRARE_PASTRIES}) { for (int resid : list) { opts.inBitmap = loaded; loaded = BitmapFactory.decodeResource(res, resid, opts); final BitmapDrawable d = new BitmapDrawable(res, convertToAlphaMask(loaded)); d.setColorFilter(new ColorMatrixColorFilter(ALPHA_MASK)); d.setBounds(0, 0, mCellSize, mCellSize); mDrawables.append(resid, d); } } loaded = null; if (DEBUG) setWillNotDraw(false); }
@Override public Drawable getDrawable(final String source) { try { Drawable repositoryImage = requestRepositoryImage(source); if (repositoryImage != null) return repositoryImage; } catch (Exception e) { // Ignore and attempt request over regular HTTP request } try { String logMessage = "Loading image: " + source; Log.d(getClass().getSimpleName(), logMessage); Bugsnag.leaveBreadcrumb(logMessage); Request request = new Request.Builder().get().url(source).build(); com.squareup.okhttp.Response response = okHttpClient.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected response code: " + response.code()); Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream()); if (bitmap == null) return loading.getDrawable(source); BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap); drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); return drawable; } catch (IOException e) { Log.e(getClass().getSimpleName(), "Error loading image", e); Bugsnag.notify(e); return loading.getDrawable(source); } }
private void startDragAtPosition(int position) { if (position != -1) { clickPosition = position; originPosition = position; } clickView = getChildAt( position - getFirstVisiblePosition()); // 任何情况下,getChildAt(int // position)返回的item都是指的可视区域内的第position个元素 if (clickView != null) { mMobileItemId = getAdapter().getItemId(position); int w = clickView.getWidth() + 100; int h = clickView.getHeight() + 100; int left = clickView.getLeft() - 50; int top = clickView.getTop() - 50; Bitmap bitmap = getBitmapFromView(clickView); bitmapDrawable = new BitmapDrawable(getResources(), bitmap); bitmapDrawable.setAlpha(150); originRect = new Rect(left, top, left + w, top + h); currentRect = new Rect(originRect); bitmapDrawable.setBounds(originRect); clickView.setVisibility(View.INVISIBLE); isEditMode = true; } }
private Bitmap mask(Bitmap image, Bitmap mask) { // todo: image wiederholen und skalierung richtig Bitmap bitmapOut = Bitmap.createBitmap(mask.getWidth(), mask.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmapOut); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); if (tileImage) { BitmapDrawable background = new BitmapDrawable(image); // in this case, you want to tile the entire view background.setBounds(0, 0, mask.getWidth(), mask.getHeight()); background.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT); background.draw(canvas); } else { canvas.drawBitmap(image, (int) (mask.getWidth() * 0.5 - image.getWidth() * 0.5), 0, paint); } Paint xferPaint = new Paint(Paint.ANTI_ALIAS_FLAG); xferPaint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); canvas.drawBitmap(mask, 0, 0, xferPaint); xferPaint.setXfermode(null); return bitmapOut; }
public Drawable getDrawable(String source) { File output = null; if (destroyed) { return loading.getDrawable(source); } try { output = File.createTempFile("image", ".jpg", dir); InputStream is = fetch(source); if (is != null) { boolean success = FileUtils.save(output, is); if (success) { Bitmap bitmap = ImageUtils.getBitmap(output, width, Integer.MAX_VALUE); if (bitmap == null) { return loading.getDrawable(source); } loadedBitmaps.add(new WeakReference<Bitmap>(bitmap)); BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap); drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); return drawable; } else { return loading.getDrawable(source); } } else { return loading.getDrawable(source); } } catch (IOException e) { return loading.getDrawable(source); } finally { if (output != null) output.delete(); } }
public NullMarker(GeoPoint point, String title, String snippet) { super(point, title, snippet); Bitmap bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565); BitmapDrawable bd = new BitmapDrawable(bitmap); bd.setBounds(0, 0, 0, 0); marker = bd; }
@Override protected void onBoundsChange(Rect bounds) { super.onBoundsChange(bounds); image.setBounds(bounds); if (placeholder != null) { // Center placeholder inside the image bounds setBounds(placeholder); } }
@Override protected void onDraw(Canvas canvas) { if (isVisible) { selectionArea.setBounds( selectionAreaPositionX, selectionAreaPositionY, SELECTION_AREA_WIDTH + selectionAreaPositionX, SELECTION_AREA_HEIGHT + selectionAreaPositionY); selectionArea.draw(canvas); } }
@Override protected void initSize() { super.initSize(); if (placeholderLineDrawable == null) { placeholderLineDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.placeholder_line); } Bitmap bitmap = placeholderLineDrawable.getBitmap(); placeholderLineDrawable.setBounds(new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight())); placeholderLineDrawableWidth = bitmap.getWidth() * 3; }
@Override public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { super.onProvideShadowMetrics(shadowSize, shadowTouchPoint); // Double the height and width int height = getView().getHeight() * 2; int width = getView().getWidth() * 2; mBitmapDrawable.setBounds(0, 0, width, height); shadowSize.set(width, height); // Set the touch point to the middle shadowTouchPoint.set(width / 2, height / 2); }
private BitmapDrawable createFloatingBitmap(View v) { floatingItemStatingBounds = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom()); floatingItemBounds = new Rect(floatingItemStatingBounds); Bitmap bitmap = Bitmap.createBitmap( floatingItemStatingBounds.width(), floatingItemStatingBounds.height(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); v.draw(canvas); BitmapDrawable retDrawable = new BitmapDrawable(v.getResources(), bitmap); retDrawable.setBounds(floatingItemBounds); return retDrawable; }
/** * Creates the hover cell with the appropriate bitmap and of appropriate size. The hover cell's * BitmapDrawable is drawn on top of the bitmap every single time an invalidate call is made. */ private BitmapDrawable getAndAddHoverView(View v) { int w = v.getWidth(); int h = v.getHeight(); int top = v.getTop(); int left = v.getLeft(); Bitmap b = getBitmapFromView(v); BitmapDrawable drawable = new BitmapDrawable(getResources(), b); mHoverCellOriginalBounds = new Rect(left, top, left + w, top + h); mHoverCellCurrentBounds = new Rect(mHoverCellOriginalBounds); drawable.setBounds(mHoverCellCurrentBounds); return drawable; }
@Override public void onTouchEvent(RecyclerView rv, MotionEvent e) { debugLog("onTouchEvent"); if ((e.getAction() == MotionEvent.ACTION_UP) || (e.getAction() == MotionEvent.ACTION_CANCEL)) { if ((e.getAction() == MotionEvent.ACTION_UP) && selectedDragItemPos != -1) { int newPos = getNewPostion(rv); if (moveInterface != null) moveInterface.onItemMoved(selectedDragItemPos, newPos); } setIsDragging(false); selectedDragItemPos = -1; floatingItem = null; rv.invalidateItemDecorations(); return; } fingerY = (int) e.getY(); if (floatingItem != null) { floatingItemBounds.top = fingerY - fingerOffsetInViewY; if (floatingItemBounds.top < -floatingItemStatingBounds.height() / 2) // Allow half the view out the top floatingItemBounds.top = -floatingItemStatingBounds.height() / 2; floatingItemBounds.bottom = floatingItemBounds.top + floatingItemStatingBounds.height(); floatingItem.setBounds(floatingItemBounds); } // Do auto scrolling at end of list float scrollAmount = 0; if (fingerY > (rv.getHeight() * (1 - autoScrollWindow))) { scrollAmount = (fingerY - (rv.getHeight() * (1 - autoScrollWindow))); } else if (fingerY < (rv.getHeight() * autoScrollWindow)) { scrollAmount = (fingerY - (rv.getHeight() * autoScrollWindow)); } debugLog("Scroll: " + scrollAmount); scrollAmount *= autoScrollSpeed; rv.scrollBy(0, (int) scrollAmount); rv.invalidateItemDecorations(); // Redraw }
/** 初始化各元素位置,大小 */ protected void genRects() { Log.e("tttt", "view_height : " + view_height); /** 顶部logo大小,宽度是屏幕宽度三分之一 */ int logo_width = image_logo.getIntrinsicWidth(); int logo_height = image_logo.getIntrinsicHeight(); int logo_target_width = view_width / 2; int logo_target_height = logo_height * logo_target_width / logo_width; /** 顶部logo位置,x轴是二分之一,y轴是三分之一 */ rect_logo = new Rect(); rect_logo.left = view_width / 2 - logo_target_width / 2; rect_logo.right = view_width / 2 + logo_target_width / 2; rect_logo.top = view_height / 2 - logo_target_height / 2; rect_logo.bottom = view_height / 2 + logo_target_height / 2; image_logo.setBounds(rect_logo); }
/** * Request an image using the contents API if the source URI is a path to a file already in the * repository * * @param source * @return * @throws IOException */ private Drawable requestRepositoryImage(final String source) throws IOException { if (TextUtils.isEmpty(source)) return null; Uri uri = Uri.parse(source); if (!HOST_DEFAULT.equals(uri.getHost())) return null; List<String> segments = uri.getPathSegments(); if (segments.size() < 5) return null; String prefix = segments.get(2); // Two types of urls supported: // github.com/github/android/raw/master/app/res/drawable-xhdpi/app_icon.png // github.com/github/android/blob/master/app/res/drawable-xhdpi/app_icon.png?raw=true if (!("raw".equals(prefix) || ("blob".equals(prefix) && !TextUtils.isEmpty(uri.getQueryParameter("raw"))))) return null; String owner = segments.get(0); if (TextUtils.isEmpty(owner)) return null; String name = segments.get(1); if (TextUtils.isEmpty(name)) return null; String branch = segments.get(3); if (TextUtils.isEmpty(branch)) return null; StringBuilder path = new StringBuilder(segments.get(4)); for (int i = 5; i < segments.size(); i++) { String segment = segments.get(i); if (!TextUtils.isEmpty(segment)) path.append('/').append(segment); } if (TextUtils.isEmpty(path)) return null; List<RepositoryContents> contents = service.getContents(RepositoryId.create(owner, name), path.toString(), branch); if (contents != null && contents.size() == 1) { byte[] content = Base64.decode(contents.get(0).getContent(), DEFAULT); Bitmap bitmap = ImageUtils.getBitmap(content, width, MAX_VALUE); if (bitmap == null) return loading.getDrawable(source); BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap); drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); return drawable; } else return null; }
@Override public View getChildView( int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { View view = getCustomChildView(); TextView titleView = (TextView) view.findViewById(R.id.HistoryRow_Title); HistoryItem item = (HistoryItem) getChild(groupPosition, childPosition); titleView.setText(item.getTitle()); TextView urlView = (TextView) view.findViewById(R.id.HistoryRow_Url); urlView.setText(item.getUrl()); CheckBox bookmarkStar = (CheckBox) view.findViewById(R.id.HistoryRow_BookmarkStar); bookmarkStar.setTag(item.getId()); bookmarkStar.setOnCheckedChangeListener(null); bookmarkStar.setChecked(item.isBookmark()); bookmarkStar.setOnCheckedChangeListener(mBookmarkStarChangeListener); ImageView faviconView = (ImageView) view.findViewById(R.id.HistoryRow_Thumbnail); Bitmap favicon = item.getFavicon(); if (favicon != null) { BitmapDrawable icon = new BitmapDrawable(favicon); Bitmap bm = Bitmap.createBitmap(mFaviconSize, mFaviconSize, Bitmap.Config.ARGB_4444); Canvas canvas = new Canvas(bm); icon.setBounds(0, 0, mFaviconSize, mFaviconSize); icon.draw(canvas); faviconView.setImageBitmap(bm); } else { faviconView.setImageResource(R.drawable.fav_icn_unknown); } return view; }
public void setPicture(String copyright, BitmapDrawable picture) { if (copyright != null && !copyright.trim().isEmpty() && picture != null) { Object[] result = getBreakerText( copyright.trim(), ProgramTableLayoutConstants.COLUMN_WIDTH - mStartTimeBounds.width() - ProgramTableLayoutConstants.TIME_TITLE_GAP, ProgramTableLayoutConstants.NOT_EXPIRED_PICTURE_COPYRIGHT_PAINT); mPictureCopyright = result[0].toString(); mSuperSmallCount += (Integer) result[1]; mPicture = picture; float percent = mPicture.getBounds().width() / (float) (getTextWidth() - mStartTimeBounds.width() - ProgramTableLayoutConstants.TIME_TITLE_GAP); if (percent > 1) { mPicture.setBounds( 0, 0, (int) (mPicture.getBounds().width() / percent), (int) (mPicture.getBounds().height() / percent)); } if (isExpired()) { if (SettingConstants.IS_DARK_THEME) { mPicture.setColorFilter( getResources().getColor(org.tvbrowser.tvbrowser.R.color.dark_gray), PorterDuff.Mode.DARKEN); } else { mPicture.setColorFilter( getResources().getColor(android.R.color.darker_gray), PorterDuff.Mode.LIGHTEN); } } } }
public XImageSpan createAndPutChipForUser(TLRPC.User user) { LayoutInflater lf = (LayoutInflater) ApplicationLoader.applicationContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); View textView = lf.inflate(R.layout.group_create_bubble, null); TextView text = (TextView) textView.findViewById(R.id.bubble_text_view); String name = ContactsController.formatName(user.first_name, user.last_name); if (name.length() == 0 && user.phone != null && user.phone.length() != 0) { name = PhoneFormat.getInstance().format("+" + user.phone); } text.setText(name + ", "); int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); textView.measure(spec, spec); textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight()); Bitmap b = Bitmap.createBitmap(textView.getWidth(), textView.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(b); canvas.translate(-textView.getScrollX(), -textView.getScrollY()); textView.draw(canvas); textView.setDrawingCacheEnabled(true); Bitmap cacheBmp = textView.getDrawingCache(); Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true); textView.destroyDrawingCache(); final BitmapDrawable bmpDrawable = new BitmapDrawable(b); bmpDrawable.setBounds(0, 0, b.getWidth(), b.getHeight()); SpannableStringBuilder ssb = new SpannableStringBuilder(""); XImageSpan span = new XImageSpan(bmpDrawable, ImageSpan.ALIGN_BASELINE); allSpans.add(span); selectedContacts.put(user.id, span); for (ImageSpan sp : allSpans) { ssb.append("<<"); ssb.setSpan( sp, ssb.length() - 2, ssb.length(), SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE); } userSelectEditText.setText(ssb); userSelectEditText.setSelection(ssb.length()); return span; }
public Drawable getDrawable(String source) { File output = null; try { output = File.createTempFile("image", ".jpg", dir); HttpRequest request = createRequest(source); if (!request.ok()) throw new IOException("Unexpected response code: " + request.code()); request.receive(output); Bitmap bitmap = ImageUtils.getBitmap(output, width, MAX_VALUE); if (bitmap == null) return loading.getDrawable(source); BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap); drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); return drawable; } catch (IOException e) { return loading.getDrawable(source); } catch (HttpRequestException e) { return loading.getDrawable(source); } finally { if (output != null) output.delete(); } }
private void processImageResponse(String id, ImageResponse response) { if (response != null) { Bitmap bitmap = response.getBitmap(); if (bitmap != null) { BitmapDrawable drawable = new BitmapDrawable(UserSettingsFragment.this.getResources(), bitmap); drawable.setBounds( 0, 0, getResources() .getDimensionPixelSize( R.dimen.com_facebook_usersettingsfragment_profile_picture_width), getResources() .getDimensionPixelSize( R.dimen.com_facebook_usersettingsfragment_profile_picture_height)); userProfilePic = drawable; userProfilePicID = id; connectedStateLabel.setCompoundDrawables(null, drawable, null, null); connectedStateLabel.setTag(response.getRequest().getImageUri()); } } }
@Override protected void onFinishInflate() { super.onFinishInflate(); titleTextView = (TextView) findViewById(R.id.list_item_title); captionView = findViewById(R.id.list_item_caption); captionTextView = (TextView) findViewById(R.id.list_item_caption_text); countTextView = (TextView) findViewById(R.id.list_item_caption_count); logoView = (ImageView) findViewById(R.id.podcast_logo); progressView = (HorizontalProgressView) findViewById(R.id.podcast_list_item_progress); // Create the class handle to star drawable if we are first if (starDrawable == null) { starDrawable = (BitmapDrawable) ContextCompat.getDrawable(getContext(), R.drawable.ic_media_new); final int size = starDrawable.getIntrinsicHeight() / 2; // The bounds need to be set to the smaller size starDrawable.setBounds(0, 0, size, size); } // Apply the star icon countTextView.setCompoundDrawables(starDrawable, null, null, null); countTextView.setCompoundDrawablePadding(0); }
@Override protected void onHandleMessageFromFragment(Message msg) { if (msg.what == 1) { isLoading = true; refresh.setBackgroundResource(R.mipmap.ic_refresh_close); } else if (msg.what == 2) { isLoading = false; refresh.setBackgroundResource(R.mipmap.ic_refresh); } else if (msg.what == 3) { int newProgress = (int) msg.obj; if (newProgress == 100) pb_bar.setVisibility(View.GONE); else pb_bar.setVisibility(View.VISIBLE); pb_bar.setProgress(newProgress); } else if (msg.what == 4) { Bitmap icon = (Bitmap) msg.obj; BitmapDrawable drawable = new BitmapDrawable(getResources(), icon); drawable.setBounds(0, 0, CommonUtils.dp2px(20), CommonUtils.dp2px(20)); // setTitle.setCompoundDrawables(drawable, null, null, null); } else if (msg.what == 5) { String title = (String) msg.obj; titles.add(" " + title); setTitle(" " + title); } }
@Override public void setBounds(Rect r) { mDrawable.setBounds(r); super.setBounds(r); }
@Override public void setBounds(int left, int top, int right, int bottom) { mDrawable.setBounds(left, top, right, bottom); super.setBounds(left, top, right, bottom); }
public Bitmap generateWidgetPreview( ComponentName provider, int previewImage, int iconId, int cellHSpan, int cellVSpan, int maxPreviewWidth, int maxPreviewHeight, Bitmap preview, int[] preScaledWidthOut) { // Load the preview image if possible String packageName = provider.getPackageName(); if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE; if (maxPreviewHeight < 0) maxPreviewHeight = Integer.MAX_VALUE; Drawable drawable = null; if (previewImage != 0) { drawable = mPackageManager.getDrawable(packageName, previewImage, null); if (drawable == null) { Log.w( TAG, "Can't load widget preview drawable 0x" + Integer.toHexString(previewImage) + " for provider: " + provider); } } int previewWidth; int previewHeight; Bitmap defaultPreview = null; boolean widgetPreviewExists = (drawable != null); if (widgetPreviewExists) { previewWidth = drawable.getIntrinsicWidth(); previewHeight = drawable.getIntrinsicHeight(); } else { // Generate a preview image if we couldn't load one if (cellHSpan < 1) cellHSpan = 1; if (cellVSpan < 1) cellVSpan = 1; BitmapDrawable previewDrawable = (BitmapDrawable) mContext.getResources().getDrawable(R.drawable.widget_tile); final int previewDrawableWidth = previewDrawable.getIntrinsicWidth(); final int previewDrawableHeight = previewDrawable.getIntrinsicHeight(); previewWidth = previewDrawableWidth * cellHSpan; previewHeight = previewDrawableHeight * cellVSpan; defaultPreview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888); final Canvas c = mCachedAppWidgetPreviewCanvas.get(); c.setBitmap(defaultPreview); previewDrawable.setBounds(0, 0, previewWidth, previewHeight); previewDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT); previewDrawable.draw(c); c.setBitmap(null); // Draw the icon in the top left corner int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage); int smallestSide = Math.min(previewWidth, previewHeight); float iconScale = Math.min((float) smallestSide / (mAppIconSize + 2 * minOffset), 1f); try { Drawable icon = null; int hoffset = (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2); int yoffset = (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2); if (iconId > 0) icon = mIconCache.getFullResIcon(packageName, iconId); if (icon != null) { renderDrawableToBitmap( icon, defaultPreview, hoffset, yoffset, (int) (mAppIconSize * iconScale), (int) (mAppIconSize * iconScale)); } } catch (Resources.NotFoundException e) { } } // Scale to fit width only - let the widget preview be clipped in the // vertical dimension float scale = 1f; if (preScaledWidthOut != null) { preScaledWidthOut[0] = previewWidth; } if (previewWidth > maxPreviewWidth) { scale = maxPreviewWidth / (float) previewWidth; } if (scale != 1f) { previewWidth = (int) (scale * previewWidth); previewHeight = (int) (scale * previewHeight); } // If a bitmap is passed in, we use it; otherwise, we create a bitmap of the right size if (preview == null) { preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888); } // Draw the scaled preview into the final bitmap int x = (preview.getWidth() - previewWidth) / 2; if (widgetPreviewExists) { renderDrawableToBitmap(drawable, preview, x, 0, previewWidth, previewHeight); } else { final Canvas c = mCachedAppWidgetPreviewCanvas.get(); final Rect src = mCachedAppWidgetPreviewSrcRect.get(); final Rect dest = mCachedAppWidgetPreviewDestRect.get(); c.setBitmap(preview); src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight()); dest.set(x, 0, x + previewWidth, previewHeight); Paint p = mCachedAppWidgetPreviewPaint.get(); if (p == null) { p = new Paint(); p.setFilterBitmap(true); mCachedAppWidgetPreviewPaint.set(p); } c.drawBitmap(defaultPreview, src, dest, p); c.setBitmap(null); } return preview; }
private void drawDrawable(Canvas canvas, Drawable drawable, int alpha) { if (drawable instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; Paint paint = bitmapDrawable.getPaint(); boolean hasFilter = paint != null && paint.getColorFilter() != null; if (hasFilter && !isPressed) { bitmapDrawable.setColorFilter(null); } else if (!hasFilter && isPressed) { bitmapDrawable.setColorFilter( new PorterDuffColorFilter(0xffdddddd, PorterDuff.Mode.MULTIPLY)); } if (colorFilter != null) { bitmapDrawable.setColorFilter(colorFilter); } if (bitmapShader != null) { drawRegion.set(imageX, imageY, imageX + imageW, imageY + imageH); if (isVisible) { roundRect.set(drawRegion); shaderMatrix.reset(); shaderMatrix.setRectToRect(bitmapRect, roundRect, Matrix.ScaleToFit.FILL); bitmapShader.setLocalMatrix(shaderMatrix); roundPaint.setAlpha(alpha); canvas.drawRoundRect(roundRect, roundRadius, roundRadius, roundPaint); } } else { int bitmapW; int bitmapH; if (orientation == 90 || orientation == 270) { bitmapW = bitmapDrawable.getIntrinsicHeight(); bitmapH = bitmapDrawable.getIntrinsicWidth(); } else { bitmapW = bitmapDrawable.getIntrinsicWidth(); bitmapH = bitmapDrawable.getIntrinsicHeight(); } float scaleW = bitmapW / (float) imageW; float scaleH = bitmapH / (float) imageH; if (isAspectFit) { float scale = Math.max(scaleW, scaleH); canvas.save(); bitmapW /= scale; bitmapH /= scale; drawRegion.set( imageX + (imageW - bitmapW) / 2, imageY + (imageH - bitmapH) / 2, imageX + (imageW + bitmapW) / 2, imageY + (imageH + bitmapH) / 2); bitmapDrawable.setBounds(drawRegion); try { bitmapDrawable.setAlpha(alpha); bitmapDrawable.draw(canvas); } catch (Exception e) { if (bitmapDrawable == currentImage && currentKey != null) { ImageLoader.getInstance().removeImage(currentKey); currentKey = null; } else if (bitmapDrawable == currentThumb && currentThumbKey != null) { ImageLoader.getInstance().removeImage(currentThumbKey); currentThumbKey = null; } setImage( currentImageLocation, currentHttpUrl, currentFilter, currentThumb, currentThumbLocation, currentThumbFilter, currentSize, currentExt, currentCacheOnly); FileLog.e("tmessages", e); } canvas.restore(); } else { if (Math.abs(scaleW - scaleH) > 0.00001f) { canvas.save(); canvas.clipRect(imageX, imageY, imageX + imageW, imageY + imageH); if (orientation != 0) { if (centerRotation) { canvas.rotate(orientation, imageW / 2, imageH / 2); } else { canvas.rotate(orientation, 0, 0); } } if (bitmapW / scaleH > imageW) { bitmapW /= scaleH; drawRegion.set( imageX - (bitmapW - imageW) / 2, imageY, imageX + (bitmapW + imageW) / 2, imageY + imageH); } else { bitmapH /= scaleW; drawRegion.set( imageX, imageY - (bitmapH - imageH) / 2, imageX + imageW, imageY + (bitmapH + imageH) / 2); } if (orientation == 90 || orientation == 270) { int width = (drawRegion.right - drawRegion.left) / 2; int height = (drawRegion.bottom - drawRegion.top) / 2; int centerX = (drawRegion.right + drawRegion.left) / 2; int centerY = (drawRegion.top + drawRegion.bottom) / 2; bitmapDrawable.setBounds( centerX - height, centerY - width, centerX + height, centerY + width); } else { bitmapDrawable.setBounds(drawRegion); } if (isVisible) { try { bitmapDrawable.setAlpha(alpha); bitmapDrawable.draw(canvas); } catch (Exception e) { if (bitmapDrawable == currentImage && currentKey != null) { ImageLoader.getInstance().removeImage(currentKey); currentKey = null; } else if (bitmapDrawable == currentThumb && currentThumbKey != null) { ImageLoader.getInstance().removeImage(currentThumbKey); currentThumbKey = null; } setImage( currentImageLocation, currentHttpUrl, currentFilter, currentThumb, currentThumbLocation, currentThumbFilter, currentSize, currentExt, currentCacheOnly); FileLog.e("tmessages", e); } } canvas.restore(); } else { canvas.save(); if (orientation != 0) { if (centerRotation) { canvas.rotate(orientation, imageW / 2, imageH / 2); } else { canvas.rotate(orientation, 0, 0); } } drawRegion.set(imageX, imageY, imageX + imageW, imageY + imageH); if (orientation == 90 || orientation == 270) { int width = (drawRegion.right - drawRegion.left) / 2; int height = (drawRegion.bottom - drawRegion.top) / 2; int centerX = (drawRegion.right + drawRegion.left) / 2; int centerY = (drawRegion.top + drawRegion.bottom) / 2; bitmapDrawable.setBounds( centerX - height, centerY - width, centerX + height, centerY + width); } else { bitmapDrawable.setBounds(drawRegion); } if (isVisible) { try { bitmapDrawable.setAlpha(alpha); bitmapDrawable.draw(canvas); } catch (Exception e) { if (bitmapDrawable == currentImage && currentKey != null) { ImageLoader.getInstance().removeImage(currentKey); currentKey = null; } else if (bitmapDrawable == currentThumb && currentThumbKey != null) { ImageLoader.getInstance().removeImage(currentThumbKey); currentThumbKey = null; } setImage( currentImageLocation, currentHttpUrl, currentFilter, currentThumb, currentThumbLocation, currentThumbFilter, currentSize, currentExt, currentCacheOnly); FileLog.e("tmessages", e); } } canvas.restore(); } } } } else { drawRegion.set(imageX, imageY, imageX + imageW, imageY + imageH); drawable.setBounds(drawRegion); if (isVisible) { try { drawable.setAlpha(alpha); drawable.draw(canvas); } catch (Exception e) { FileLog.e("tmessages", e); } } } }
@Override public BitmapDrawable getDrawable(String url) { Bitmap imagePre = null; String dirName = null; String fileName = null; String fileNameSec = null; if (url == null || url.length() == 0) { return null; } final String[] urlParts = url.split("\\."); String urlExt = null; if (urlParts.length > 1) { urlExt = "." + urlParts[(urlParts.length - 1)]; if (urlExt.length() > 5) { urlExt = ""; } } else { urlExt = ""; } if (geocode != null && geocode.length() > 0) { dirName = settings.getStorage() + geocode + "/"; fileName = settings.getStorage() + geocode + "/" + cgBase.md5(url) + urlExt; fileNameSec = settings.getStorageSec() + geocode + "/" + cgBase.md5(url) + urlExt; } else { dirName = settings.getStorage() + "_others/"; fileName = settings.getStorage() + "_others/" + cgBase.md5(url) + urlExt; fileNameSec = settings.getStorageSec() + "_others/" + cgBase.md5(url) + urlExt; } File dir = null; dir = new File(settings.getStorage()); if (dir.exists() == false) dir.mkdirs(); dir = new File(dirName); if (dir.exists() == false) dir.mkdirs(); dir = null; try { final File file = new File(fileName); final File fileSec = new File(fileNameSec); if (file.exists() == true) { final long imageSize = file.length(); // large images will be downscaled on input to save memory if (imageSize > (6 * 1024 * 1024)) { bfOptions.inSampleSize = 48; } else if (imageSize > (4 * 1024 * 1024)) { bfOptions.inSampleSize = 16; } else if (imageSize > (2 * 1024 * 1024)) { bfOptions.inSampleSize = 10; } else if (imageSize > (1 * 1024 * 1024)) { bfOptions.inSampleSize = 6; } else if (imageSize > (0.5 * 1024 * 1024)) { bfOptions.inSampleSize = 2; } if (reason > 0 || file.lastModified() > ((new Date()).getTime() - (24 * 60 * 60 * 1000))) { imagePre = BitmapFactory.decodeFile(fileName, bfOptions); } } else if (fileSec.exists() == true) { final long imageSize = fileSec.length(); // large images will be downscaled on input to save memory if (imageSize > (6 * 1024 * 1024)) { bfOptions.inSampleSize = 48; } else if (imageSize > (4 * 1024 * 1024)) { bfOptions.inSampleSize = 16; } else if (imageSize > (2 * 1024 * 1024)) { bfOptions.inSampleSize = 10; } else if (imageSize > (1 * 1024 * 1024)) { bfOptions.inSampleSize = 6; } else if (imageSize > (0.5 * 1024 * 1024)) { bfOptions.inSampleSize = 2; } if (reason > 0 || file.lastModified() > ((new Date()).getTime() - (24 * 60 * 60 * 1000))) { imagePre = BitmapFactory.decodeFile(fileNameSec, bfOptions); } } } catch (Exception e) { Log.w(cgSettings.tag, "cgHtmlImg.getDrawable (reading cache): " + e.toString()); } if (imagePre == null && reason == 0) { Uri uri = null; HttpClient client = null; HttpGet getMethod = null; HttpResponse httpResponse = null; HttpEntity entity = null; BufferedHttpEntity bufferedEntity = null; try { // check if uri is absolute or not, if not attach geocaching.com hostname and scheme uri = Uri.parse(url); if (uri.isAbsolute() == false) { url = "http://www.geocaching.com" + url; } } catch (Exception e) { Log.e(cgSettings.tag, "cgHtmlImg.getDrawable (parse URL): " + e.toString()); } if (uri != null) { for (int i = 0; i < 2; i++) { if (i > 0) Log.w( cgSettings.tag, "cgHtmlImg.getDrawable: Failed to download data, retrying. Attempt #" + (i + 1)); try { client = new DefaultHttpClient(); getMethod = new HttpGet(url); httpResponse = client.execute(getMethod); entity = httpResponse.getEntity(); bufferedEntity = new BufferedHttpEntity(entity); final long imageSize = bufferedEntity.getContentLength(); // large images will be downscaled on input to save memory if (imageSize > (6 * 1024 * 1024)) { bfOptions.inSampleSize = 48; } else if (imageSize > (4 * 1024 * 1024)) { bfOptions.inSampleSize = 16; } else if (imageSize > (2 * 1024 * 1024)) { bfOptions.inSampleSize = 10; } else if (imageSize > (1 * 1024 * 1024)) { bfOptions.inSampleSize = 6; } else if (imageSize > (0.5 * 1024 * 1024)) { bfOptions.inSampleSize = 2; } Log.i(cgSettings.tag, "[" + entity.getContentLength() + "B] Downloading image " + url); if (bufferedEntity != null) imagePre = BitmapFactory.decodeStream(bufferedEntity.getContent(), null, bfOptions); if (imagePre != null) break; } catch (Exception e) { Log.e(cgSettings.tag, "cgHtmlImg.getDrawable (downloading from web): " + e.toString()); } } } try { // save to memory/SD cache if (bufferedEntity != null) { final InputStream is = (InputStream) bufferedEntity.getContent(); final FileOutputStream fos = new FileOutputStream(fileName); try { final byte[] buffer = new byte[4096]; int l; while ((l = is.read(buffer)) != -1) fos.write(buffer, 0, l); } catch (IOException e) { Log.e(cgSettings.tag, "cgHtmlImg.getDrawable (saving to cache): " + e.toString()); } finally { is.close(); fos.flush(); fos.close(); } } } catch (Exception e) { Log.e(cgSettings.tag, "cgHtmlImg.getDrawable (saving to cache): " + e.toString()); } entity = null; bufferedEntity = null; } if (onlySave == false) { if (imagePre == null) { Log.d(cgSettings.tag, "cgHtmlImg.getDrawable: Failed to obtain image"); if (placement == false) { imagePre = BitmapFactory.decodeResource(activity.getResources(), R.drawable.image_no_placement); } else { imagePre = BitmapFactory.decodeResource(activity.getResources(), R.drawable.image_not_loaded); } } Display display = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); final int imgWidth = imagePre.getWidth(); final int imgHeight = imagePre.getHeight(); final int maxWidth = display.getWidth() - 25; final int maxHeight = display.getHeight() - 25; int width = imgWidth; int height = imgHeight; double ratio = 1.0d; if (imgWidth > maxWidth || imgHeight > maxHeight) { if ((maxWidth / imgWidth) > (maxHeight / imgHeight)) { ratio = (double) maxHeight / (double) imgHeight; } else { ratio = (double) maxWidth / (double) imgWidth; } width = (int) Math.ceil(imgWidth * ratio); height = (int) Math.ceil(imgHeight * ratio); try { imagePre = Bitmap.createScaledBitmap(imagePre, width, height, true); } catch (Exception e) { Log.d(cgSettings.tag, "cgHtmlImg.getDrawable: Failed to scale image"); return null; } } final BitmapDrawable image = new BitmapDrawable(imagePre); image.setBounds(new Rect(0, 0, width, height)); return image; } return null; }
@Override public boolean onTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: Log.d("zyr", "onTouchEvent ACTION_DOWN"); originX = ev.getX(); originY = ev.getY(); if (isEditMode) { clickPosition = pointToPosition((int) originX, (int) originY); Log.d("zyr", "clickPosition:" + clickPosition); layoutChildren(); startDragAtPosition(); } break; case MotionEvent.ACTION_MOVE: Log.d("zyr", "onTouchEvent ACTION_MOVE"); currentX = ev.getX(); currentY = ev.getY(); deltaX = currentX - originX; deltaY = currentY - originY; if (isEditMode) { /** *******************************镜像随手指移动********************************* */ currentRect.offsetTo(originRect.left + (int) deltaX, originRect.top + (int) deltaY); bitmapDrawable.setBounds(currentRect); invalidate(); /** *******************************实时交换动画********************************* */ targetPosition = pointToPosition((int) currentX, (int) currentY); if (this.swapListener != null && isEditMode && targetPosition != -1 && originPosition != targetPosition) { Log.d( "zyrr", "originPosition:" + originPosition + " targetPosition:" + targetPosition); swapListener.onSwap(originPosition, targetPosition); getChildAt(originPosition - getFirstVisiblePosition()).setVisibility(VISIBLE); getChildAt(targetPosition - getFirstVisiblePosition()).setVisibility(INVISIBLE); animateReorder(targetPosition, originPosition); originPosition = targetPosition; } /** *******************************到边界向上滚动或者向下滚动********************************* */ int offset = computeVerticalScrollOffset(); int height = getHeight(); int extent = computeVerticalScrollExtent(); int range = computeVerticalScrollRange(); int hoverViewTop = currentRect.top; int hoverHeight = currentRect.height(); if (hoverViewTop <= 0 && offset > 0) { smoothScrollBy(-24, 0); return true; } if (hoverViewTop + hoverHeight >= height && (offset + extent) < range) { smoothScrollBy(24, 0); return true; } } break; case MotionEvent.ACTION_UP: Log.d("zyr", "onTouchEvent ACTION_UP"); bitmapDrawable = null; if (clickView != null) { clickView.setVisibility(VISIBLE); } if (getChildAt(originPosition - getFirstVisiblePosition()) != null) { getChildAt(originPosition - getFirstVisiblePosition()).setVisibility(VISIBLE); } upPosition = pointToPosition((int) currentX, (int) currentY); if (this.actionUpListener != null && isEditMode && upPosition != -1) { actionUpListener.onActionUp(clickPosition, upPosition); } isEditMode = false; break; } return super.onTouchEvent(ev); }