当前位置:网站首页>ImageView grayed, reflected, rounded, watermarked
ImageView grayed, reflected, rounded, watermarked
2022-06-12 22:23:00 【Hua Weiyun】
Android In development , Some small experience , If there is no summary record in time , So next time you meet , The same search thinking test , This takes a lot of time , The efficiency is not high ,ImageView Is a particularly commonly used control , The picture is rounded 、 Add watermark 、 Graying is also a particularly common requirement , In fact, the code is so fixed for a few lines , Let's look at the specific implementation .
The sample original used in this article :

Let's deal with this picture into various styles .
Convert color pictures to gray pictures

/** * Convert a color image into a grayscale image * @param img Bitmap * @return Returns the converted bitmap */ public Bitmap convertGreyImg(Bitmap img) { int width = img.getWidth(); // Get the width of the bitmap int height = img.getHeight(); // Gets the height of the bitmap int []pixels = new int[width * height]; // Create an array of pixels by the size of the bitmap img.getPixels(pixels, 0, width, 0, 0, width, height); int alpha = 0xFF << 24; for(int i = 0; i < height; i++) { for(int j = 0; j < width; j++) { int grey = pixels[width * i + j]; int red = ((grey & 0x00FF0000 ) >> 16); int green = ((grey & 0x0000FF00) >> 8); int blue = (grey & 0x000000FF); grey = (int)((float) red * 0.3 + (float)green * 0.59 + (float)blue * 0.11); grey = alpha | (grey << 16) | (grey << 8) | grey; pixels[width * i + j] = grey; } } Bitmap result = Bitmap.createBitmap(width, height, Config.RGB_565); result.setPixels(pixels, 0, width, 0, 0, width, height); return result; }Turn the picture into a rounded corner

public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output;}Add a reflection effect to the picture

/** * How to get a picture with reflection */public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) { final int reflectionGap = 4; int width = bitmap.getWidth(); int height = bitmap.getHeight(); Matrix matrix = new Matrix(); matrix.preScale(1, -1); Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2, width, height / 2, matrix, false); Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Config.ARGB_8888); Canvas canvas = new Canvas(bitmapWithReflection); canvas.drawBitmap(bitmap, 0, 0, null); Paint deafalutPaint = new Paint(); canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint); canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null); Paint paint = new Paint(); LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP); paint.setShader(shader); // Set the Transfer mode to be porter duff and destination in paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); // Draw a rectangle using the paint with our linear gradient canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint); return bitmapWithReflection;}Add watermark

/** * * @param src * Image to add watermark * @param watermark * @return Watermarked pictures */private Bitmap createBitmap(Bitmap src, Bitmap watermark) { String tag = "createBitmap"; Log.d(tag, "create a new bitmap"); if (src == null) { return null; } int w = src.getWidth(); int h = src.getHeight(); int ww = watermark.getWidth(); int wh = watermark.getHeight(); // create the new blank bitmap Bitmap newb = Bitmap.createBitmap(w, h, Config.ARGB_8888);// Create a new and SRC Bitmap with the same length and width Canvas cv = new Canvas(newb); // draw src into cv.drawBitmap(src, 0, 0, null);// stay 0,0 The coordinates begin to draw into src // draw watermark into cv.drawBitmap(watermark, w - ww + 5, h - wh + 5, null);// stay src Draw a watermark in the lower right corner of the // save all clip cv.save(Canvas.ALL_SAVE_FLAG);// preservation // store cv.restore();// Storage return newb;}Generate pictures :View Turn into Bitmap
/** * Put one View The object of is converted to bitmap */static Bitmap getViewBitmap(View v) { v.clearFocus(); v.setPressed(false); // If you can draw the cache, you will return false boolean willNotCache = v.willNotCacheDrawing(); v.setWillNotCacheDrawing(false); int color = v.getDrawingCacheBackgroundColor(); v.setDrawingCacheBackgroundColor(0); if (color != 0) { v.destroyDrawingCache(); } v.buildDrawingCache(); Bitmap cacheBitmap = v.getDrawingCache(); if (cacheBitmap == null) { Log.e(TAG, "failed getViewBitmap(" + v + ")", new RuntimeException()); return null; } Bitmap bitmap = Bitmap.createBitmap(cacheBitmap); // Restore the view v.destroyDrawingCache(); v.setWillNotCacheDrawing(willNotCache); v.setDrawingCacheBackgroundColor(color); return bitmap;}summary
Last one The blog summarizes two unusual layout techniques , This article summarizes and records about ImageView Of 5 Three transformation techniques , It can be used as a knowledge base , With the accumulation of working experience , Every developer should have their own knowledge base , It is convenient to improve development efficiency , To sum up your experience .
I am an Android Development Engineer , I'm studying recently Java Back end knowledge , Keep learning every day , It doesn't take long to master a skill , come on. !
边栏推荐
- Have you really learned the common ancestor problem recently?
- Palindrome linked list and linked list intersection problem (intersecting with Xinyi people) do you really know?
- Things about the kotlin collaboration process - pipeline channel
- 四元数简介
- JS fighting on...
- Lambda expression and flow optimization code
- You can move forward or backward. This function in idea is amazing!
- web3 原则和去中心化
- be careful! Your Navicat may have been poisoned
- QT quick 3D learning: use mouse and keyboard to control node position and direction
猜你喜欢

年薪50万是一条线,年薪100万又是一条线…...

数据库每日一题---第10天:组合两个表

基于51单片机的酒精检测仪

NoSQL - redis configuration and optimization (II) high availability, persistence and performance management

JVM foundation > G1 garbage collector

Audio and video technology development weekly 𞓜 234

Have you really learned the common ancestor problem recently?

Shardingsphere-proxy-5.0.0 deployment table implementation (I)

【Web技术】1348- 聊聊水印实现的几种方式

Redis optimization
随机推荐
How to abstract a problem into a 0-1 knapsack problem in dynamic programming
【LeetCode】5. 最长回文子串
About the solution to "the application cannot start normally 0xc00000022" after qt5.15.2 is installed and qtcreator is started
孙老师版本JDBC(2022年6月12日21:34:25)
3.5 setup and teardown of test classes
talent showing itself! Oceanbase was selected into the 2021 "sci tech innovation China" open source innovation list
leetcodeSQL:574. Elected
[proteus simulation] simple digital tube timer clock
接口测试工具apipost3.0版本对于流程测试和引用参数变量
The interface testing tool apipos3.0 is applicable to process testing and reference parameter variables
How to perform disaster recovery and recovery for kubernetes cluster? (22)
Yyds dry goods inventory solution sword finger offer: the first non repeated character in the character stream
China barcode decoder market trend report, technical innovation and market forecast
Palindrome linked list and linked list intersection problem (intersecting with Xinyi people) do you really know?
RAID disk array
The programmer dedicated to promoting VIM has left. Father of vim: I will dedicate version 9.0 to him
Ansible playbook and variable (II)
【LeetCode】69. Square root of X
How to develop programming learning with zero foundation during college
The kotlin coroutine -- coroutine context and exception propagation